输入模块是早期版本 Python 的后向端口,用于推断输入和输出数据类型。我在让它在 Python 2.7 中工作时遇到问题。
import typing
def greeting(name): # type: (str) -> str
"""documentations"""
return ('Hello ' + name)
print(greeting.__annotations__) # fails because doesn't exist.
Run Code Online (Sandbox Code Playgroud)
我也试过这个:
import typing
def greeting(name # type: str
):
# type: (...) -> str
"""documentations"""
return ('Hello ' + name)
Run Code Online (Sandbox Code Playgroud)
和这个:
import typing
def greeting(name):
# type: (str) -> str
"""documentations"""
return ('Hello ' + name)
Run Code Online (Sandbox Code Playgroud)
这应该__annotations__
根据 PEP484 在类上创建一个属性,但我根本没有看到这种情况发生。
向后移植代码有什么问题?
typing
是在 Python 3.5 中引入的模块。PEP 484 中的示例依赖于 Python 3+,并且__annotations__
是 Python 3 概念。backport 只能允许使用定义在typing
模块中,但它不会改变 Python 引擎来神奇地理解所有 Python 3 概念。
另一篇SO 帖子中的讨论表明,应该可以通过使用inspect.getsourcelines
来研究函数声明之后的第一行并以 # 类型开头来访问注释。typed-ast
pypi 上存在一个模块,应该能够解析 Python 2.7 样式的注释。不幸的是,它仅在 beta 级别声明并且仅与 Python 3 兼容。
归档时间: |
|
查看次数: |
8805 次 |
最近记录: |