Skip to main content

Don't forget `py.typed` for your typed Python package


Excerpts from Don’t forget py.typed for your typed Python package | whtsky’s blog by :

Intro

pixelmatch-py, a Python library I maintained for comparing images, received a Pull Request to add type hints about 10 months ago. After merging this PR & releasing a new version, I thought the library’s users will magically get their type working.

Until today, I was reading cryptography’s Changelog and a line got my attention:

Added a py.typed file so that mypy will know to use our type annotations.

After reading PEP-561 and mypy documentation I’m sure that I didn’t publish the package right: I should include a py.typed file, or the type checker won’t use the type hints provided by the package.

Adding py.typed

It’s faily simple to include this file: just touch a py.typed file in your package directory and include it in your distribution.
I’m using poetry, so I added

1 2 3 4toml packages = [ {include = "pixelmatch"}, {include = "pixelmatch/py.typed"}, ]

under the [tool.poetry] section of pyproject.toml.

Update: As pointed out by Jürgen Gmach, poetry includes all files in your packages (including py.typed file!) by default, so there’s no need to include the file manually.

If you’re using setup.py, you can add package_data to setup call:

1 2 3python setup( package_data={"pixelmatch": ["py.typed"]}, )

Release a new version for your package then type informations from your packages should works.

Fin

If you’re a Python package maintainer, be sure to include py.typed file for your typed package!