Checking if a type is generic and correct type hint #1132
-
Hi, (I am using Python 3.7.9) I have a function that takes a type and checks if it's generic: def is_generic(t: type):
return hasattr(t, "__origin__") First question: is Then I have a function that checks the non-parameterized generic class for a type: def is_generic_of(t: object, origin: object) -> bool:
return is_generic(t) and t.__origin__ == origin # type: ignore
# Example: is_generic_of(List[str], list) == True The thing is I don't know how to access the field def is_union(t: object):
return is_generic_of(t, Union)
def is_optional(t: object) -> bool:
return is_union(t) and t.__args__[1] == type(None) # type: ignore I found that Any thoughts on this? Thanks! ;) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I'd suggest you use a library like https://github.com/ilevkivskyi/typing_inspect. You can also |
Beta Was this translation helpful? Give feedback.
I'd suggest you use a library like https://github.com/ilevkivskyi/typing_inspect. You can also
typing_extensions.get_origin
andget_args
(backports of https://docs.python.org/3.10/library/typing.html#typing.get_args).