type hinting backward compatibility with python 3.0 to 3.4

Edward Ned Harvey (python) python at nedharvey.com
Fri May 19 09:35:13 EDT 2017


I think it's great that for built-in types such as int and str, backward compatibility of type hinting annotations is baked into python 3.0 to 3.4. In fact, I *thought* python 3.0 to 3.4 would *ignore* annotations, but it doesn't...

I'm struggling to create something backward compatible that requires the 'typing' module. For example, the following program is good in python 3.5, but line 11 is a syntax error in python 3.4:

     1 import sys 
     2 
     3 if sys.version_info[0] < 3:
     4     raise RuntimeError("Must use at least python version 3") 
     5 
     6 # The 'typing' module, useful for type hints, was introduced in python 3.5 
     7 if sys.version_info[1] >= 5: 
     8     from typing import Optional
     9     
    10 
    11 def divider(x: int, y: int) -> Optional[float]:
    12     if y == 0: 
    13         return None
    14     return x / y
    15     
    16 print("22 / 7 = " + str(divider(22, 7)))
    17 print("8 / 0 = " + str(divider(8, 0)))
    18

When I run this program in python 3.4, I get this:
    Traceback (most recent call last):
      File "./ned.py", line 11, in <module>
        def divider(x: int, y: int) -> Optional[float]:
    NameError: name 'Optional' is not defined



More information about the Python-list mailing list