[英]Python 3 type hints in Python 2
I have python def
definition which seems working for python3:我有似乎适用于 python3 的 python
def
定义:
def get_default_device(use_gpu: bool = True) -> cl.Device:
Under python2 I get the following syntax error:在 python2 下,我收到以下语法错误:
root:~/pyopencla/ch3# python map_copy.py
Traceback (most recent call last):
File "map_copy.py", line 9, in <module>
import utility
File "/home/root/pyopencla/ch3/utility.py", line 6
def get_default_device(use_gpu: bool = True) -> cl.Device:
^
SyntaxError: invalid syntax
How to make type hints compatible with python2?如何使类型提示与python2兼容?
Function annotations were introduced in PEP 3107 for Python 3.0. Python 3.0 的PEP 3107中引入了函数注释。 The usage of annotations as type hints was formalized in in PEP 484 for Python 3.5+.
注释作为类型提示的使用在 Python 3.5+ 的PEP 484 中正式化。
Any version before 3.0 then will not support the syntax you are using for type hints at all. 3.0 之前的任何版本都将根本不支持您用于类型提示的语法。 However, PEP 484 offers a workaround , which some editors may choose to honor.
但是,PEP 484 提供了一种解决方法,一些编辑可能会选择尊重它。 In your case, the hints would look like this:
在您的情况下,提示如下所示:
def get_default_device(use_gpu=True):
# type: (bool) -> cl.Device
...
or more verbosely,或更详细地说,
def get_default_device(use_gpu=True # type: bool
):
# type: (...) -> cl.Device
...
The PEP explicitly states that this form of type hinting should work for any version of Python, if it is supported at all. PEP 明确指出,这种形式的类型提示应该适用于任何版本的 Python,如果它受支持的话。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.