python - 函数参数类型设置返回 SyntaxError

标签 python python-2.7 function types arguments

我有一个 python 脚本,其中包含如下函数参数的类型声明:

def dump_var(v: Variable, name: str = None):

据我所知,这是一个为函数设置输入参数类型的有效语法,但它返回一个

SyntaxError: invalid syntax

可能出了什么问题?

最佳答案

SyntaxError 是因为 Python 2.7 不支持类型提示。您可以使用 Python 3.5+ 或使用 Python 2.7 的类型提示在评论中 作为 PEP 484建议:

Suggested syntax for Python 2.7 and straddling code

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>

关于python - 函数参数类型设置返回 SyntaxError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41929413/

相关文章:

python - 基本的 wx 大小问题

python - 如何将 xlib 和 OpenGL 模块与 python 一起使用?

python - 为数据框创建 Parquet 创建函数

python - WTForms:如果数据存在,则用数据填充表单

python - 如何获取列中的最新时间戳?

python - 如何在 GTK 中更新绘图区域

function - 连接器作为模型中的函数输入参数

c - 在 C 中通过调用函数(按值传递)进行打印

python - MySQL 5.6 中的全局查询超时

python - 感知器学习算法需要大量迭代才能收敛?