0
votes

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
By removing the type hints - Brad Solomon

1 Answers

1
votes

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.