gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:30:51 29 4
gpt4 key购买 nike

我有一个 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/

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