如何在Python中在运行时从存根文件(.pyi)中获取类型注释?

我想在函数或类方法中获取注释.如果类型提示是在源代码中编写的,那么我可以通过获取属性__annotations__来获取类型.

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

但我不知道如何使用存根文件(.pyi)编写类型.

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

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

有什么很酷的方法吗?

最佳答案 从
PEP-484开始:

Stub files are files containing type hints that are only for use by the type checker, not at runtime. There are several use cases for stub files:

  • Extension modules
  • Third-party modules whose authors have not yet added type hints
  • Standard library modules for which type hints have not yet been written
  • Modules that must be compatible with Python 2 and 3
  • Modules that use annotations for other purposes

所以不幸的是,没有办法获得注释以及如何解释它们由类型检查器自行决定.这有副作用,没有权威资源来验证您的类型提示是否正确.

最接近的是mypy.

点赞