gpt4 book ai didi

python - Python 2 中的类型提示

转载 作者:IT老高 更新时间:2023-10-28 21:49:03 24 4
gpt4 key购买 nike

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

最佳答案

根据Suggested syntax for Python 2.7 and straddling code在定义类型提示的 PEP 484 中,有一种与 Python 2.7 兼容的替代语法。但是它不是强制性的,所以我不知道它的支持程度,但引用 PEP:

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>

is equivalent to the following:

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

关于 mypy 支持,请参阅 Type checking Python 2 code .

关于python - Python 2 中的类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35230635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com