Identifying Generic Types at Runtime #1099
Unanswered
hmc-cs-mdrissi
asked this question in
Q&A
Replies: 1 comment 2 replies
-
I'll leave my current solution here. It works for the test cases I have listed, although I'd be happily surprised if there aren't harder edge cases I'm missing. def _type_var_present(tp: object) -> bool:
# Add TypeVarTuple eventually
if isinstance(tp, (TypeVar, Paramspec)):
return True
args = get_args(tp)
if args is None:
return False
return any(_type_var_present(arg) for arg in args)
def is_generic(cls: object) -> bool:
if hasattr(cls, "__parameters__") and len(cls.__parameters__) > 0: # type: ignore
return True
if isinstance(cls, _SpecialForm):
return cls._name in ("Union", "Optional", "Literal") # type: ignore
if get_origin(cls) is None:
return False
args = get_args(cls)
# Only at top level is no args parametrizable. list is parametrizable, but list[list] is not.
if len(args) == 0:
return True
return _type_var_present(cls) |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Is there a recommended public/stableish api way of identifying if a type is generic at runtime? Here I'm thinking of a type being generic if it accepts type parameters. I've included some example test cases describing behavior I'm aiming for.
The intended use case is for non-generic types I "fully" know type and use that information for serialization/deserialization. For generic types I instead need a function that takes as argument all types needed to fill in unknown type parameters and uses that to make a serializer/deserializer. So I'm roughly looking for objects, t, where t[int] makes sense as a type annotation.
Beta Was this translation helpful? Give feedback.
All reactions