How to get type annotation from stub files (.pyi) at runtime in Python?

I want to get annotations in functions or methods of a class. If the hintings types are written in source code, I can get the types by getting the attribute __annotations__.

def hoge(n: int): ...
print(hoge.__annotations__)  # {'n': <class 'int'>}

But I don’t know how to get types written in stub files (.pyi).

# .pyi
def fuga(n: int): ...

# .py
def fuga(n): ...
print(fuga.__annotations__)  # {}

Is there any cool method?

+4
source share
1 answer

From PEP-484 :

Stub files are files containing type hints that are used only for type checking, but not at runtime. There are several options for using stub files:

  • Expansion Modules
  • ,
  • ,
  • , Python 2 3
  • ,

, , , . , .

mypy.

+1

Source: https://habr.com/ru/post/1684268/


All Articles