在Python 2中键入提示

And*_*rew 39 python types type-hinting python-2.7

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

Mij*_*amo 60

根据Python 2.7的推荐语法和定义类型提示的PEP 484中的跨越代码,有一种与Python 2.7兼容的替代语法.然而,这不是强制性的,所以我不知道支持得多好,但引用了PEP:

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

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

相当于以下内容:

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

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


小智 11

此时推荐和python3兼容的方法是遵循python2到3指南:http://python-future.org/func_annotations.html

def embezzle(self, account: str, funds: int = 1000000, *fake_receipts: str) -> None:
    """Embezzle funds from account using fake receipts."""
    pass
Run Code Online (Sandbox Code Playgroud)

成为:

def embezzle(self, account, funds = 1000000, *fake_receipts):
    """Embezzle funds from account using fake receipts."""
    pass
embezzle.__annotations__ = {'account': str, 'funds': int, 'fake_receipts': str, 'return': None}
Run Code Online (Sandbox Code Playgroud)

  • 这不适用于非文字类型,例如“列表”,“集合” (2认同)