osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

type hinting backward compatibility with python 3.0 to 3.4


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)))