Python 3 type hints in Python 2

岁酱吖の 提交于 2020-02-16 08:23:13

问题


I have python def definition which seems working for python3:

def get_default_device(use_gpu: bool = True) -> cl.Device:

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

How to make type hints compatible with python2?


回答1:


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+.

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
    ...

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.



来源:https://stackoverflow.com/questions/53306458/python-3-type-hints-in-python-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!