Skip to content

Commit

Permalink
Raise TypeError when TypeAliasType is subscripted without having type…
Browse files Browse the repository at this point in the history
…_params (#473)

Co-authored-by: Alex Waygood <[email protected]>
  • Loading branch information
Daraan and AlexWaygood authored Sep 26, 2024
1 parent b6c0558 commit 2c84de1
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
by PEP 649. Patches by Jelle Zijlstra and Alex Waygood.
- Copy the coroutine status of functions and methods wrapped
with `@typing_extensions.deprecated`. Patch by Sebastian Rittau.
- Fix bug where `TypeAliasType` instances could be subscripted even
where they were not generic. Patch by [Daraan](https://github.com/Daraan).

# Release 4.12.2 (June 7, 2024)

Expand Down
14 changes: 14 additions & 0 deletions src/test_typing_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -7247,6 +7247,20 @@ def test_getitem(self):
self.assertEqual(get_args(fully_subscripted), (Iterable[float],))
self.assertIs(get_origin(fully_subscripted), ListOrSetT)

def test_subscription_without_type_params(self):
Simple = TypeAliasType("Simple", int)
with self.assertRaises(TypeError, msg="Only generic type aliases are subscriptable"):
Simple[int]

# A TypeVar in the value does not allow subscription
T = TypeVar('T')
MissingTypeParamsErr = TypeAliasType("MissingTypeParamsErr", List[T])
self.assertEqual(MissingTypeParamsErr.__type_params__, ())
self.assertEqual(MissingTypeParamsErr.__parameters__, ())
with self.assertRaises(TypeError, msg="Only generic type aliases are subscriptable"):
MissingTypeParamsErr[int]


def test_pickle(self):
global Alias
Alias = TypeAliasType("Alias", int)
Expand Down
2 changes: 2 additions & 0 deletions src/typing_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3525,6 +3525,8 @@ def __repr__(self) -> str:
return self.__name__

def __getitem__(self, parameters):
if not self.__type_params__:
raise TypeError("Only generic type aliases are subscriptable")
if not isinstance(parameters, tuple):
parameters = (parameters,)
parameters = [
Expand Down

0 comments on commit 2c84de1

Please sign in to comment.