Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mypy: Raise TypeError during execution

Context

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.

Question

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.

like image 278
Daniel Lenz Avatar asked Oct 28 '25 17:10

Daniel Lenz


2 Answers

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.

like image 69
MrLeeh Avatar answered Oct 31 '25 06:10

MrLeeh


You can self call to mypy or use a similar approach. I put this in the head of my scripts to automate the process of checking before running the program.

import os, sys

def enforce_type_checking() -> None:
    result : int = os.system("mypy \"" + __file__ + "\""
        + " --strict --strict-equality --extra-checks"
        + " --pretty --show-error-context --show-column-numbers"
        + " --warn-return-any --warn-unreachable"
        + " --disallow-any-unimported --disallow-any-expr --disallow-any-decorated --disallow-any-explicit --disallow-any-generics --disallow-subclassing-any"
        + " --disallow-untyped-calls --disallow-untyped-defs --disallow-incomplete-defs --check-untyped-defs --disallow-untyped-decorators"
        + " --cache-dir \"" + sys.path[0] + "\" --install-types"
    )
    if result: input("Press <ENTER> to continue...")

# program #####################################################################

enforce_type_checking()

print("hello world")
like image 33
Leonel Avatar answered Oct 31 '25 06:10

Leonel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!