Mypy is interpreting missing symbols as `Any`?

Python 3.11, mypy 1.15.0

Simple setup.
test.py:

from test_package import weird_symbol

def test(d: weird_symbol[str, list[int]]):
    print(d.items())
    reveal_type(d)

test_package located in site-packages that has 3 files: __init__.py, py.typed (both just empty files) and __init__.pyi:

from collections import defaultdict as weird_symbol

__all__ = ['weird_symbol']

Running mypy check on this have this result:

> py -3.11 -m mypy test.py
test.py:5: note: Revealed type is "collections.defaultdict[builtins.str, builtins.list[builtins.int]]"
Success: no issues found in 1 source file

But if we mess with a stub file a bit making it import unknown symbol

from collections_ import defaultdict as weird_symbol

__all__ = ['weird_symbol']

There will be no errors, it will just interpret unknown symbol as Any. Is it normal? I expected it to fail at least in some way indicating that there’s a missing symbol.

py -3.11 -m mypy test.py
test.py:5: note: Revealed type is "Any"
Success: no issues found in 1 source file

Why it’s important - noticed this because one of the files had something like from typing import TypeIs (which is only available in Python 3.12) which led to some false negatives because some symbols were just replaced with Any and had no real effect.

Yes, mypy usually does not report errors in installed packages to users.

You could probably change this using some combination of the advanced and very-easy-to-incorrectly-use per-module options follow_imports + follow_imports_for_stubs.

For your use case when the stub is something mypy will check, this is what I get:

λ cat y.pyi
from typing import TypeIs

λ python3.11 -m mypy y.pyi
y.pyi:1: error: Module "typing" has no attribute "TypeIs"  [attr-defined]
y.pyi:1: note: Use `from typing_extensions import TypeIs` instead
y.pyi:1: note: See https://mypy.readthedocs.io/en/stable/runtime_troubles.html#using-new-additions-to-the-typing-module
Found 1 error in 1 file (checked 1 source file)

Yeah, it does work perfectly for running mypy directly on some file or if importing local modules.

I’ve found the solution for my problem - the way to unsupress the errors from packages imported from site-packages is to set no_silence_site_packages flag, which is disabled by default (The mypy configuration file - mypy 1.15.0 documentation).

1 Like