Skip to content

Commit 2c84de1

Browse files
DaraanAlexWaygood
andauthored
Raise TypeError when TypeAliasType is subscripted without having type_params (#473)
Co-authored-by: Alex Waygood <[email protected]>
1 parent b6c0558 commit 2c84de1

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
by PEP 649. Patches by Jelle Zijlstra and Alex Waygood.
88
- Copy the coroutine status of functions and methods wrapped
99
with `@typing_extensions.deprecated`. Patch by Sebastian Rittau.
10+
- Fix bug where `TypeAliasType` instances could be subscripted even
11+
where they were not generic. Patch by [Daraan](https://github.com/Daraan).
1012

1113
# Release 4.12.2 (June 7, 2024)
1214

src/test_typing_extensions.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7247,6 +7247,20 @@ def test_getitem(self):
72477247
self.assertEqual(get_args(fully_subscripted), (Iterable[float],))
72487248
self.assertIs(get_origin(fully_subscripted), ListOrSetT)
72497249

7250+
def test_subscription_without_type_params(self):
7251+
Simple = TypeAliasType("Simple", int)
7252+
with self.assertRaises(TypeError, msg="Only generic type aliases are subscriptable"):
7253+
Simple[int]
7254+
7255+
# A TypeVar in the value does not allow subscription
7256+
T = TypeVar('T')
7257+
MissingTypeParamsErr = TypeAliasType("MissingTypeParamsErr", List[T])
7258+
self.assertEqual(MissingTypeParamsErr.__type_params__, ())
7259+
self.assertEqual(MissingTypeParamsErr.__parameters__, ())
7260+
with self.assertRaises(TypeError, msg="Only generic type aliases are subscriptable"):
7261+
MissingTypeParamsErr[int]
7262+
7263+
72507264
def test_pickle(self):
72517265
global Alias
72527266
Alias = TypeAliasType("Alias", int)

src/typing_extensions.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3525,6 +3525,8 @@ def __repr__(self) -> str:
35253525
return self.__name__
35263526

35273527
def __getitem__(self, parameters):
3528+
if not self.__type_params__:
3529+
raise TypeError("Only generic type aliases are subscriptable")
35283530
if not isinstance(parameters, tuple):
35293531
parameters = (parameters,)
35303532
parameters = [

0 commit comments

Comments
 (0)