I'm testing the typing features of ^Python3.6 however it seems like it's not doing anything, I can do this without getting an error:
my_var: int = 0
my_var = 'str'
# no error
def ret_var(my_var: int) -> int:
return my_var
ret_var(my_var)
# also no error
how can I get this throw an exception or at least a warning ?
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.