The following script contains an intentional type error:
def foo(x, y):
print(x[:y])
def main():
foo('abcde', '2')
if __name__ == "__main__":
main()
The error can be confirmed by running it:
$ python3 untyped_test.py
Traceback (most recent call last):
File "untyped_test.py", line 8, in <module>
main()
File "untyped_test.py", line 5, in main
foo('abcde', '2')
File "untyped_test.py", line 2, in foo
print(x[:y])
TypeError: slice indices must be integers or None or have an __index__ method
However I was hoping to catch something like this not only at runtime but before executing the code using:
mypy --check-untyped-defs untyped_test.py
But it does not find any errors:
$ mypy --check-untyped-defs untyped_test.py
$ mypy --version
mypy 0.590
Only when I annotate foo:
def foo(x: str, y: int):
print(x[:y])
I get:
untyped_test.py:5: error: Argument 2 to "foo" has incompatible type "str"; expected "int"
Is it possible to find errors like this without any manual type annotations?
foo('abcde', '2')→foo('abcde', 2)mypycan find it. I will adjust the question to clarify this.mypyas possible. Every Python user is free to choose not to do type checking, and instead wait until the error explodes at runtime right in front of the customer. ;)