Python:函数参数类型设置返回语法错误 [英] Python: function parameter type-setting returning syntaxerror
问题描述
我有一个 python 脚本,其中包含函数参数的类型声明,如下所示:
I have a python script that contains a type declaration of function arguments as following:
def dump_var(v: Variable, name: str = None):
据我所知,这是一种为函数设置输入参数类型的有效语法,但它返回一个
To my knowledge, this is a valid syntax that sets a type of input parameters to the function, but it returns a
SyntaxError: invalid syntax
可能有什么问题?
推荐答案
Short Answer : SyntaxError: invalid syntax ,因为 for python2.7 类型提示是语法违规 ,您可以在评论中使用 python3.5+ 或使用 python2.7 的类型提示作为 PEP 建议
Short Answer : SyntaxError: invalid syntax ,because the for python2.7 type hint is a syntax violation ,you may either use python3.5+ or use type hints for python2.7 in comments as PEP suggests
您可以阅读本文以了解如何在 python2.7 中进行类型提示 python2.7 和跨界 clode 的建议语法.
You may read this to know how to do type hints in python2.7 Suggested syntax for python2.7 and straddling clode.
某些工具可能希望支持代码中的类型注释,这些注释必须是与 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)
示例:
以下 Python 3 代码:
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>
相当于下面的python 2.7代码
is equivalent to the following python 2.7 code
def embezzle(self, account, funds=1000000, *fake_receipts):
# type: (str, int, *str) -> None
"""Embezzle funds from account using fake receipts."""
<code goes here>
这篇关于Python:函数参数类型设置返回语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!