Python 2中的Python 3类型提示

Python 2中的Python 3类型提示,python,python-3.x,python-2.x,python-typing,Python,Python 3.x,Python 2.x,Python Typing,我有pythondefdefinition,它似乎适用于python3: def get_default_device(use_gpu: bool = True) -> cl.Device: 在python2下,我得到以下语法错误: root:~/pyopencla/ch3# python map_copy.py Traceback (most recent call last): File "map_copy.py", line 9, in <module> i

我有python
def
definition,它似乎适用于python3:

def get_default_device(use_gpu: bool = True) -> cl.Device:
在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
root:~/pyopencla/ch3#python map_copy.py
回溯(最近一次呼叫最后一次):
文件“map_copy.py”,第9行,在
导入实用程序
文件“/home/root/pyopencla/ch3/utility.py”,第6行
def get_default_设备(使用_gpu:bool=True)->cl.设备:
^
SyntaxError:无效语法

如何使类型提示与python2兼容?

函数注释是在python3.0中引入的。注释作为类型提示的使用在Python3.5+中被形式化

3.0之前的任何版本都不支持您用于类型提示的语法。然而,一些编辑可能会选择尊重PEP 484。在您的情况下,提示如下所示:

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,如果它完全受支持的话。

通过删除类型暗示,在这种情况下,PEP484可能不是相关的源代码。类型提示只是函数注释的一个应用程序,由Python 3.0引入。@chepner。我已经更新了。虽然我同意自Py 3.0以来注释是有效的,但相关的PEP仍然是484(参考3107)。但是为什么它们不允许并忽略py2中的语法,以便您至少可以使用相同的源代码?@Trass3r。我不认为有一个来自未来导入的
选项,因为它会涉及对解释器进行太多的更改。