如何在Python 2.7中使用函数注释

问题描述 投票:0回答:2

我在Ipython中看到了这个源代码:

https://github.com/ipython/ipython/blob/e1e2e960315f0f98703f6b8b077b10c99d04d70a/IPython/core/completer.py#L314

我知道这是 python3 中一个名为

Function Annotation
的新功能。

但是这段代码也可以在 Python 2.7 中运行。为什么?

如何在 Python 2.7 中使用

Function Annotation

python python-2.7 ipython python-typing
2个回答
4
投票

您不能直接在 2.7 中使用新的(3.5+)注释语法,但如果您有 python 3.4+,您可以安装 mypy 并使用不同的语法在 2.7 代码上运行它。请参阅PEP 484

您在链接中指向的示例可以在 2.7 中编写为:

class Completion:
    def __init__(self, start, end, text, type=None, _origin=''):
        # type: (int, int, str, str, str) -> None
        ...

1
投票

不可以,Python 2.7 中不能使用函数注释。 也就是说,函数注释的主要用途是逐步打字,这可以通过 Python 2.7 中的注释来完成。

© www.soinside.com 2019 - 2024. All rights reserved.