How do I define a `typing.Union` dynamically?

I am using Typeguard in a couple if projects for type checking at run time in Python. It works pretty well.

I have encountered a situation where the type of a function parameter is a typing.Union made up of a few dynamically collected data types. E.g.

def find_datatypes():     # some stuff ...     return (str, int) # dynamically generated list / tuple  datatypes = find_datatypes() 

Now I want to generate a typing.Union from datatypes for eventual use in a function. I expected unpacking syntax to work:

my_union = typing.Union[*datatypes]  @typeguard.typechecked def some_function(param: my_union):     pass 

However, it did not:

    my_union = typing.Union[*datatypes]                             ^ SyntaxError: invalid syntax 

How would I achieve what I want?

Asked on July 15, 2020 in Python.
Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.