type hinting backward compatibility with python 3.0 to 3.4

Edward Ned Harvey (python) python at nedharvey.com
Fri May 19 10:19:20 EDT 2017


This pattern seems to work:

import sys

if sys.version_info[0] < 3:
    raise RuntimeError("Must use at least python version 3")

# The 'typing' module, useful for type hints, was introduced in python 3.5
if sys.version_info[1] >= 5:
    from typing import Optional
    optional_float = Optional[float]
else:
    optional_float = object

def divider(x: int, y: int) -> optional_float:
    if y == 0:
        return None
    return x / y

print("3 / 0 = " + str(divider(3,0)))
print("22 / 7 = " + str(divider(22,7)))




More information about the Python-list mailing list