typing : how to get if a class attribute is of a type alias?

Viewed 60

For example:

import typing

tuple2 = typing.Tuple[float,float]

class A:
  a: tuple2 = (1.,1.)

print(typing.get_type_hints(A)['a'])

This prints, as expected: typing.Tuple[float, float]

Does something simular to this exists?

print(some_other_function(A)['a'])
# prints: "tuple2" 
1 Answers

tuple2 is just a variable that refers to typing.Tuple[float,float]. In general, you can't get the name of a variable based on its value, unless you do weird stuff with inspecting the variable namespace.

What you might want to do is use typing.NewType to define an actual new type:

>>> Tuple2 = typing.NewType("Tuple2", typing.Tuple[float, float])
>>> class A:
...     a: Tuple2 = Tuple2((1, 1))
...
>>> typing.get_type_hints(A)['a'].__name__
'Tuple2'

Note that a NewType is not the same as an alias; type checkers will consider it to be a subtype of the type that you derive it from, so if you declare something as a Tuple2 you need to define it as Tuple2((1, 1)) rather than a regular 1, 1 tuple. In practice, the newtype always behaves exactly the same as the parent type, so if you aren't using a type checker the difference is unimportant.

If you really want to get the name of an alias, you could look at globals(), e.g.:

>>> tuple2 = typing.Tuple[float,float]
>>> [k for k, v in globals().items() if v == typing.Tuple[float, float]]
['tuple2']

but this is not great because there might well be multiple names for the same value, and if there are, there's no way at runtime to figure out which alias was used for a particular type.

Related