How to use mypy with nixpkgs? (Cannot find implementation or library stub for module)

I’m unable to get mypy to discover site packages in Python environments created with Nixpkgs. What am I missing here?

Given a simple example.py:

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name = 'Jane Doe'

If I create a normal Python virtual env, mypy --strict example.py passes as expected:

$ nix-shell -p python3 --run "python -m venv mypyenv"
$ mypyenv/bin/pip install mypy pydantic
$ mypyenv/bin/mypy --strict example.py
Success: no issues found in 1 source file

But if I use a Nixpkgs’ Python environment, mypy is unable to find third party packages, here pydantic:

$ nix-shell -p "python3.withPackages(ps: with ps; [ mypy pydantic ])" --run "mypy --strict example.py"
example.py:1: error: Cannot find implementation or library stub for module named 'pydantic'
example.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports
example.py:3: error: Class cannot subclass 'BaseModel' (has type 'Any')
Found 2 errors in 1 file (checked 1 source file)

What commit of nixpkgs are you on? I believe mypy was broken until
recently (Python: introduce NIX_PYTHONPREFIX in order to set site.PREFIXES by adisbladis · Pull Request #82453 · NixOS/nixpkgs · GitHub).

1 Like

Thanks! I was on NixOS 20.03 and completely unaware that mypy was known to be broken.

My example worked on the latest master:

$ nix-shell -I "nixpkgs=https://github.com/NixOS/nixpkgs/archive/4bf632f495a7bdd5fe46575b36d8e772ed804f8b.tar.gz" -p "python3.withPackages(ps: with ps; [ mypy pydantic ])" --run "mypy --strict example.py"
Success: no issues found in 1 source file