I have a list of type objects and want to construct a typing.Tuple object. Is there a way to do this?
tys = [int, str] # This is known only at runtime
x = typing.Tuple(tys) # TypeError: Type Tuple cannot be instantiated; use tuple() instead
Any help will be appreciated. Thanks.
Edit: For clarification about the question-
What I am trying to do - visit a Tuple in python AST and annotate its type. For this the list tys
is made out of a loop (and so, I could not start with a tuple in the start). Now, I definitely have to annotate it with a typing.Tuple
object and hence the question.
I got the solution.
x = typing.Tuple[tuple(tys)] # This works
Edit: This works for all typing constructs. For eg. while typing.Union(tys)
and typing.Union[tys]
will give an error, typing.Union[tuple(tys)]
works. I am not sure if this is a general "python" thing, or it is special with the typing module. I will update this answer once I know that.