【问题标题】:Using typing module in Python 2.7在 Python 2.7 中使用类型模块
【发布时间】:2017-06-13 03:16:43
【问题描述】:

打字模块是早期版本的 Python 推断输入和输出数据类型的后端端口。我在让它在 Python 2.7 中工作时遇到问题。

import typing
def greeting(name): # type: (str) -> str
    """documentations"""
    return ('Hello ' + name)
print(greeting.__annotations__) # fails because doesn't exist.

我也试过这个:

import typing
def greeting(name # type: str
             ):
    # type: (...) -> str
    """documentations"""
    return ('Hello ' + name)

还有这个:

import typing

def greeting(name):
    # type: (str) -> str
    """documentations"""
    return ('Hello ' + name)

这应该根据 PEP484 在类上创建一个 __annotations__ 属性,但我根本没有看到这种情况发生。

我在使用反向移植代码时做错了什么?

【问题讨论】:

  • @khelwood 这不起作用,所以如果我用类型符号做我上面所做的事情,它就不起作用。 __annotations__ 永远不会在 3.5 版本或 2.7 中获得人口
  • 您是否使用mypy --py2 program.py 之类的方式运行您的代码?如果您使用普通 Python 运行,则不会解释类型注释。
  • 您仍然需要使用 mypy 运行它。 Python 3 以普通语法引入了类型注释,但注释的东西需要由 mypy 解释。
  • 注意还有其他类型注解解释器。您不必使用 mypy。

标签: python python-2.7


【解决方案1】:

typing 是 Python 3.5 中引入的一个模块。 PEP 484 中的示例依赖于 Python 3+,__annotations__ 是 Python 3 的概念。 backport 只能允许使用 typing 模块中定义的函数类型,但它不会改变 Python 引擎以神奇地理解所有 Python 3 概念。

其他SO post 中的讨论表明,注释应该可以通过使用inspect.getsourcelines 来研究函数声明之后的第一行并以# 类型开始。 typed-ast 模块存在于 pypi 上,应该能够解析 Python 2.7 样式的注释。不幸的是,它仅在 beta 级别声明,并且仅与 Python 3 兼容。

【讨论】:

  • 那么 Python 3.5 应该理解 # type 符号吗?
  • mypy 可以在 Python 2 和 3 中解释它们,我错了吗?
猜你喜欢
  • 2016-09-16
  • 2015-06-15
  • 1970-01-01
  • 2015-04-04
  • 2017-09-12
  • 2017-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多