type hinting backward compatibility with python 3.0 to 3.4

Peter Otten __peter__ at web.de
Fri May 19 10:30:53 EDT 2017


Edward Ned Harvey (python) wrote:

> 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

Luckily it's a NameError. To backport you only have to define a symbol. The 
easiest way to do that is to get hold of a copy of 3.5's typing.py, so let's 
try that first:

$ cp /usr/local/lib/python3.5/typing.py .
$ python3.4
Python 3.4.3 (default, Nov 17 2016, 01:08:31) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from typing import Optional
>>> def divider(x: int, y: int) -> Optional[float]: pass
... 
>>> 

Works...




More information about the Python-list mailing list