Search code examples
pythonpython-typingmypy

mypy don't recognizes a typing error when it happens in a function


When I have code like this:

class C : pass

def f1( c : C ) : pass

f1( 100)

def f2( c : C = None ) : pass

f2( 100)

then mypy claims errors like this:

$ mypy 002_1.py 
002_1.py:11: error: Argument 1 to "f1" has incompatible type "int"; expected "C"
002_1.py:15: error: Argument 1 to "f2" has incompatible type "int"; expected "Optional[C]"
Found 2 errors in 1 file (checked 1 source file)

which is expected.

But when I have code like this:

class C : pass

def f1( c : C ) : pass

def f2( c : C = None ) : pass

def test001() :
 f1( 100)
 f2( 100)

test001()

then mypy don't see the error.

I am using mypy 0.812 and Python 3.9.2.

What can I do to see the typing error?


Solution

  • The behavior you're observing occurs because mypy is less strict with type checking inside functions that lack type annotations. By default, mypy focuses on checking the function signatures rather than the code within unannotated functions. This is why the errors aren't being reported when the function calls are inside test001().

    To throw an error you can add type annotations to the test001() function like None. You can manually enable strict mode in mypy will help solve the problem by enforcing more rigorous type checks, including within function bodies that lack type annotations. mypy --strict 002_1.py. You can use the --disallow-untyped-defs option with mypy will also solve the problem by requiring type annotations for all function signatures. When this option is enabled, mypy will flag any function that doesn't have type annotations, forcing you to explicitly annotate every function.

    mypy --disallow-untyped-defs 002_1.py
    mypy --check-untyped-defs 002_1.py
    

    Or --check-untyped-defswhich checks the bodies of functions without type annotations.It type checks the body of every function, regardless of whether it has type annotations. (By default the bodies of functions without annotations are not type checked.)