user3428154
user3428154

Reputation: 1344

Python 3 type hints in Python 2

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:

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?

Upvotes: 1

Views: 2619

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114310

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.

Upvotes: 1

Related Questions