Type annotations don't do anything in and of themselves to enforce types, what they do is prepare your code to be evaluated by a typechecker such as Mypy, along with allowing programmatic reading of function annotations for things like more intelligent decorators.
If you want to start enforcing types without using a type checker for some reason, you can decorate your functions. I have one such decorator available on github that supports Union[]
, Optional[]
, and Any
in addition to standard annotations:
Usage:
from type_enforcer import enforce_types
@enforce_types
def foo(x: int, y: float) -> int:
return int(x * y)
>>> try:
>>> foo(5, 2.0)
>>> except TypeError as e:
>>> print(str(e))
10
>>> try:
>>> foo(5, 2)
>>> except TypeError as e:
>>> print(str(e))
Argument y supplied wrong type: expected float, got int.