ytr*_*ewq 2 python types arguments function python-2.7
我有一个包含函数参数类型声明的 python 脚本,如下所示:
def dump_var(v: Variable, name: str = None):
Run Code Online (Sandbox Code Playgroud)
据我所知,这是一种为函数设置输入参数类型的有效语法,但它返回一个
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
可能有什么问题?
简短回答: SyntaxError: invalid syntax ,因为 for python2.7 类型提示是语法违规,您可以使用python3.5+或在注释中使用python2.7 的类型提示,如PEP建议
您可以阅读本文以了解如何在 python2.7 中为 python2.7 和跨界 clode 建议语法进行类型提示。
某些工具可能希望在必须与 Python 2.7 兼容的代码中支持类型注释。为此,这个 PEP 有一个建议的(但不是强制性的)扩展,其中函数注释被放置在 # type: 注释中。这样的注释必须紧跟在函数头之后(在文档字符串之前)
一个例子:
以下 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)
相当于下面的python 2.7代码
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)
| 归档时间: |
|
| 查看次数: |
5859 次 |
| 最近记录: |