vendredi 3 décembre 2021

How do I determine the type of a Python type annotation at runtime?

I want to inspect the type annotation of a class variable, and if it is a typing.Literal, extract the literal value and do something with it. But:

from typing import Literal
class Foo:
    bar: Literal['baz']

l = Foo.__annotations__['bar']
isinstance(l, Literal)

yields:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/tbabb/.pyenv/versions/3.8.5/lib/python3.8/typing.py", line 342, in __instancecheck__
    raise TypeError(f"{self} cannot be used with isinstance()")
TypeError: typing.Literal cannot be used with isinstance()

Also, l.__class__ == Literal is False, so that doesn't work either.

Why doesn't the isinstance() check succeed? How do I check the type of annotation that's being used?





Aucun commentaire:

Enregistrer un commentaire