Unpack Optional type annotation in Python 3.5.2

Viewed 3336

Given this example:

import typing

def foo(bar: int = None):
    pass

typing.get_type_hints(foo)

The type hint for bar is typing.Union[int, None]. How do I get int from that? Neither the __args__ nor __parameters__ property seems to work in Python 3.5.2.


More concretely, I'm trying to write a generic decorator that inspects the signature of a function and does specific things to the arguments. For that it needs to get the class from an annotation such as Optional[T] to then work with T:

annot = typing.Optional[T]
cls = # MAGIC?!
assert cls is T
2 Answers
Related