1

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 ?

khelwood
  • 55,782
  • 14
  • 81
  • 108
Konstantin Paulus
  • 1,943
  • 2
  • 10
  • 22
  • 1
    Possible duplicate of [How to use type hints in python 3.6?](https://stackoverflow.com/questions/41356784/how-to-use-type-hints-in-python-3-6) – Georgy Oct 29 '19 at 15:09
  • @Georgy I'm not sure, there's an answerable question at the end not in the linked question, specifically how to use annotations in a way that throws an exception. – Andy Oct 29 '19 at 15:20
  • @Andy I can see that in the duplicate target OP has the same request though: "_I would like the following effects: If it's obvious that I used the wrong type just as shown above, throw out a warning or error_" – Georgy Oct 29 '19 at 15:31
  • @Georgy you're right, looks like my brain skipped over that line when I was reading – Andy Oct 29 '19 at 15:34

1 Answers1

3

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.
Andy
  • 3,132
  • 4
  • 36
  • 68