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
怎么了?
推荐答案
简短回答: SyntaxError:语法无效,因为for python2.7类型的提示违反了 语法 ,您可以使用 python3.5 + 或在注释中使用 python2.7 的类型提示作为
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中键入提示
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屋!