Search code examples
pythonmypypython-typingpython-poetry

MyPy can't find types for my local package


I have two python packages. One is a util library, and one is an application that will use the util library (eventually I will have more apps sharing the library.

I am using poetry for both, and the app specifies the common library as a dependency using the path and develop properties.

For example, my layout looks something like this:

- common/
   - common/
      - __init__.py
      - py.typed
   - pyproject.toml

- myapp/
   - myapp/
      - __init__.py
      - py.typed
   - pyproject.toml

And the myapp\pyproject.toml looks something like this:

[tool.poetry]
name = "myapp"
version = "0.1.0"
description = ""
authors = ["Your Name <[email protected]>"]

[tool.poetry.dependencies]
python = "^3.9"
common = { path = "../common", develop = true }

[tool.poetry.dev-dependencies]
mypy = "^0.910"
flake8 = "^4.0.1"
black = {version = "^21.12b0", allow-prereleases = true}
pytest = "^6.2.5"
pytest-cov = "^3.0.0"
pytest-mock = "^3.6.1"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

When I run mypy on myapp I get something like:

myapp/__init__.py:1:1: error: Cannot find implementation or library stub for module named "common"  [import]

Solution

  • Assuming the "util" package has type hints, you'll want to add a py.typed file to it (in the root directory of the package) so mypy understands it comes with type hints. py.typed should be empty, it's just a flag file.

    If your package does not have type hints, then you'd have to add stubs files (.pyi).

    More details: https://mypy.readthedocs.io/en/stable/installed_packages.html#creating-pep-561-compatible-packages