Reputation: 562
I'm unable to get any information about the parameter when using typing.Union
:
import typing
x = typing.Union[str,int]
print(typing.get_args(x))
Output: (<class 'str'>, <class 'int'>)
def f(y: typing.Union[str,int]):
print(typing.get_args(y))
f(1)
Output: ()
Upvotes: 0
Views: 1269
Reputation: 3360
You can use typing.get_type_hints()
to get type annotations of f
:
def f(y: typing.Union[str,int]):
print(typing.get_type_hints(f))
f(1)
Upvotes: 0
Reputation: 18458
x
is a union of types. y
is of the union type (i.e. either of type int
or of type str
).
Try print(type(x))
and print(type(y))
.
In your function signature, you merely annotated that y
should be either of type str
or of type int
. So you'll be calling get_args
on an int
, when you pass 1
to the function.
x
in your code is just an alias for that type union object.
In fact, you could do this:
from typing import Union
x = Union[str, int]
def f(y: x):
...
This is equivalent:
from typing import Union
def f(y: Union[str, int]):
...
Upvotes: 1