Skip to content

Commit

Permalink
Handle non-indexed generics >= py3.9 (#94)
Browse files Browse the repository at this point in the history
Closes #93
This prevents `get_parameters` throwing an exception on python >= 3.9.
This does lead to a difference in behaviour between different python versions, but the new class based alias introduced in 3.9 doesn't store the required info. So to maintaining the same behaviour would require a dictionary of the generic types to the correct output.

Example of change in behaviour:
**python <=3.8**
```
>>> from typing import List
>>> from typing_inspect import get_parameters
>>> get_parameters(List)
(~T,)
```

**python >=3.9**
```
>>> from typing import List
>>> from typing_inspect import get_parameters
>>> get_parameters(List)
()
```
  • Loading branch information
jamesrobson-secondmind authored Nov 21, 2022
1 parent b24da20 commit beaa4a4
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
5 changes: 5 additions & 0 deletions test_typing_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
Union, Callable, Optional, TypeVar, Sequence, AnyStr, Mapping,
MutableMapping, Iterable, Generic, List, Any, Dict, Tuple, NamedTuple,
)
from typing import T as typing_T

from mypy_extensions import TypedDict as METypedDict
from typing_extensions import TypedDict as TETypedDict
Expand Down Expand Up @@ -354,6 +355,10 @@ def test_parameters(self):
self.assertEqual(get_parameters(Union), ())
if not LEGACY_TYPING:
self.assertEqual(get_parameters(List[int]), ())
if PY39:
self.assertEqual(get_parameters(List), ())
else:
self.assertEqual(get_parameters(List), (typing_T,))
else:
# in 3.5.3 a list has no __args__ and instead they are used in __parameters__
# in 3.5.1 the behaviour is normal again.
Expand Down
6 changes: 5 additions & 1 deletion typing_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,11 @@ def get_parameters(tp):
else:
return ()
elif NEW_TYPING:
if (isinstance(tp, typingGenericAlias) or
if (
(
isinstance(tp, typingGenericAlias) and
hasattr(tp, '__parameters__')
) or
isinstance(tp, type) and issubclass(tp, Generic) and
tp is not Generic):
return tp.__parameters__
Expand Down

0 comments on commit beaa4a4

Please sign in to comment.