Python 2 中的 Python 3 类型提示 [英] Python 3 type hints in Python 2
问题描述
我有 python def
定义,它似乎适用于 python3:
I have python def
definition which seems working for python3:
def get_default_device(use_gpu: bool = True) -> cl.Device:
在 python2 下,我收到以下语法错误:
Under python2 I get the following syntax error:
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
如何让类型提示兼容python2?
How to make type hints compatible with python2?
推荐答案
PEP 3107.注释作为类型提示的用法在 Python 的 PEP 484 中正式化3.5+.
Function annotations were introduced in PEP 3107 for Python 3.0. The usage of annotations as type hints was formalized in in PEP 484 for Python 3.5+.
3.0 之前的任何版本都将根本不支持您用于类型提示的语法.但是,PEP 484 提供了一种解决方法,一些编辑可能会选择尊重它.在您的情况下,提示如下所示:
Any version before 3.0 then will not support the syntax you are using for type hints at all. However, PEP 484 offers a workaround, which some editors may choose to honor. In your case, the hints would look like this:
def get_default_device(use_gpu=True):
# type: (bool) -> cl.Device
...
或更详细地说,
def get_default_device(use_gpu=True # type: bool
):
# type: (...) -> cl.Device
...
PEP 明确指出,这种形式的类型提示应该适用于任何版本的 Python,如果它完全受支持的话.
The PEP explicitly states that this form of type hinting should work for any version of Python, if it is supported at all.
这篇关于Python 2 中的 Python 3 类型提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!