I am doing some meta programming, and I need a way to define type hints on the fly. Is there a way to pass an array of arguments to a type hint? Something like:
# Some programatically generated list where I don't know the content until runtime
permitted_types = [int, str, bool, float, list, dict]
union = Union[*permitted_types]
The code above yields:
TypeError: Union[arg, ...]: each arg must be a type. Got [<class 'int'>, <class 'str'>, <class 'bool'>, <class 'float'>, <class 'list'>, <class 'dict'>]
Does anybody know syntax for doing this? At the moment I am reduced to the following and I hate it:
num_args = len(args)
if num_args == 1:
return origin[args[0]]
elif num_args == 2:
return origin[args[0], args[1]]
elif num_args == 3:
return origin[args[0], args[1], args[2]]
elif num_args == 4:
return origin[args[0], args[1], args[2], args[3]]
elif num_args == 5:
return origin[args[0], args[1], args[2], args[3], args[4]]
elif num_args == 6:
return origin[args[0], args[1], args[2], args[3], args[4], args[5]]
else:
# Raise error
Ok - I found the syntax by rummaging around in typing.py:
return Union[tuple(permitted_types)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With