Difference between TypeVar('T') and Any

Viewed 1789

Assuming I have some generic function:

def foo(*args):
    for arg in args:
        print(arg)

If I wanted to type hint *args, according to the PEP I only need to specify the type one arg.

What if the arguments can be of any type? What is the difference between:

T = typing.TypeVar('T')

def foo(*args: T):
    ...

and

def foo(*args: Any):
    ...

To my knowledge, TypeVar('T') equates to "any type", but does that apply when variable args are of multiple types?

1 Answers

One could think that the difference is:

foo(*args: T) means that the function can take any amount of arguments and the arguments can be of any type, but must all be of the same type.

foo(*args: Any) means that the function can take any amount of any type arguments.

But this is actually not the case: https://github.com/python/mypy/issues/6559#issuecomment-473864640

In reality there is no difference between the two definitions.

Related