Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of __name__ in TypeVar, NewType

In the typing module, both TypeVar and NewType require as a first positional argument, a string to be used as the created object's __name__ attribute. What is the purpose of __name__ here?

Considering that this is a compulsory argument, I would expect it to be something essential. In PEP-484 where type hinting was introduced, the argument is normally set as a string of the variable name assigned to the object:

T = TypeVar('T', int, float, complex)

But, I can't really tell how this end up being used in typing.py in CPython. Replacing the string with indeed any other string does not appear to break anything in my tests.

like image 476
Melvin Avatar asked Jan 24 '18 07:01

Melvin


1 Answers

The __name__ attribute is the associated typename that the IDE, for example, will use in its type hints. Given the following toy code:

T = TypeVar('not_T', int, float)
def test_func(arg: T): pass

Calling the function with something incorrect like test_func('not_a_number') would result in a type hint like this:

Expected type 'not_t', got 'str' instead

Since their main purpose is debugging, no restrictions are set on conformity between type.__name__ and the name tag you use to handle it.


For an additional use case, you can also check the types in the __annotations__ member of any object where it is used to type hint, e.g.

print(test_func.__annotations__)
>> {'arg': ~not_T}

And use that to implement further type checking or handling in your code - in which case your TypeVar.__name__s better be meaningful :)

like image 127
Arne Avatar answered Nov 14 '22 22:11

Arne