Skip to content

Commit

Permalink
Fix runtime_generic_proxy for 3.9+
Browse files Browse the repository at this point in the history
  • Loading branch information
bswck committed Feb 20, 2024
1 parent 6c17a06 commit 30a4196
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
10 changes: 9 additions & 1 deletion runtime_generics/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,15 @@ def _init_runtime_generic(cls: type[_GenericClassT], result_type: Any = None) ->

def runtime_generic_proxy(result_type: _GenericClassT) -> _GenericClassT:
"""Create a runtime generic descriptor with a result type."""
parameters = result_type.__parameters__
try:
parameters = result_type.__parameters__
except AttributeError: # smells like Python 3.9+
parameters = tuple(
map(
TypeVar,
map("T".__add__, map(str, range(1, result_type._nparams + 1))), # noqa: SLF001
),
)

@partial(runtime_generic, result_type=result_type)
class _Proxy(Generic[parameters]): # type: ignore[misc]
Expand Down
8 changes: 4 additions & 4 deletions tests/test_runtime_generics.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from typing import Any, Generic, List, TypeVar
from typing import Any, Generic, Dict, TypeVar
from typing import get_args as _typing_get_args

from typing_extensions import TypeVarTuple, Unpack
Expand Down Expand Up @@ -115,9 +115,9 @@ class HamVariadic(Generic[Unpack[Ts], T], SpamVariadic[Unpack[Ts]], Qux[T]):
pass


with runtime_generic_patch(List):
with runtime_generic_patch(Dict):
@runtime_generic
class EggsVariadic(Generic[T, T2], List[HamVariadic[T, T2]]):
class EggsVariadic(Generic[T, T2], Dict[HamVariadic[T, T2], str]):
pass


Expand Down Expand Up @@ -146,4 +146,4 @@ def test_get_parents() -> None:
assert get_parents(SpamVariadic[str, int]) == ()
assert get_parents(HamVariadic) == (SpamVariadic[Unpack[Ts]], Qux[T]) # type: ignore[valid-type]
assert get_parents(HamVariadic[float, str, bytes]) == (SpamVariadic[float, str], Qux[bytes])
assert get_parents(EggsVariadic[complex, bool]) == (List[HamVariadic[complex, bool]],)
assert get_parents(EggsVariadic[complex, bool]) == (Dict[HamVariadic[complex, bool], str],)

0 comments on commit 30a4196

Please sign in to comment.