mypy
is great to check whether types are handled correctly.
# example.py
def test(string: str):
return str
if __name__ == '__main__':
test('19')
test(19)
This will work for the first case, but not for the second one.
>> mypy example.py
example.py:6: error: Argument 1 to "test" has incompatible type "int"; expected "str"
However, just running this via
>> python example.py
does not raise any errors.
Is it possible to use the optional static typing in python to raise errors when the code is actually executed?
I was hoping to use this e.g. to check variable types in unittests
, where it would be much easier than having various if not isinstance(...)
statements.
In short: Python does not check your types even if you have included type-hints.
Type-Hinting has been introduced to provide the option for static type-checking. This helps you get rid of many errors before even running your code. But you will need to use a static type-checker like mypy to do this. Python is still a dynamically typed language and therefore doesn't do any type-checking itself.