Python 2 中的类型提示 [英] Type hinting in Python 2

查看:57
本文介绍了Python 2 中的类型提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PEP 484 中,Python 3 中添加了类型提示包含 typing 模块.有没有办法在 Python 2 中做到这一点?我所能想到的就是有一个装饰器来添加到方法来检查类型,但这会在运行时失败,并且不会像提示允许的那样更早地被捕获.

In PEP 484, type hinting was added to Python 3 with the inclusion of the typing module. Is there any way to do this in Python 2? All I can think of is having a decorator to add to methods to check types, but this would fail at runtime and not be caught earlier like the hinting would allow.

推荐答案

根据 Python 2.7 和跨界代码的建议语法 在 PEP 484 中定义了类型提示,还有一种替代语法与 Python 2.7 的兼容性.然而,这不是强制性的,所以我不知道它的支持程度如何,但引用了 PEP:

According to Suggested syntax for Python 2.7 and straddling code in PEP 484 which defined type hinting, there is an alternative syntax for compatibility with Python 2.7. It is however not mandatory so I don't know how well supported it is, but quoting the PEP:

某些工具可能希望在必须与 Python 2.7 兼容的代码中支持类型注释.为此,这个 PEP 有一个建议的(但不是强制性的)扩展,其中函数注释被放置在 # type: 注释中.这样的注释必须紧跟在函数头之后(在文档字符串之前).一个例子:下面的 Python 3 代码:

Some tools may want to support type annotations in code that must be compatible with Python 2.7. For this purpose this PEP has a suggested (but not mandatory) extension where function annotations are placed in a # type: comment. Such a comment must be placed immediately following the function header (before the docstring). An example: the following Python 3 code:

def embezzle(self, account: str, funds: int = 1000000, *fake_receipts: str) -> None:
    """Embezzle funds from account using fake receipts."""
    <code goes here>

相当于以下内容:

def embezzle(self, account, funds=1000000, *fake_receipts):
    # type: (str, int, *str) -> None
    """Embezzle funds from account using fake receipts."""
    <code goes here>

有关 mypy 的支持,请参阅 类型检查 Python 2 代码.

For mypy support, see Type checking Python 2 code.

这篇关于Python 2 中的类型提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆