Appendix: Automatic Annotations#
[Too specific to mypy--should cover other tools]
This placeholder text was generated by ChatGPT 4.5. It will be significantly rewritten as the book is developed. You can add comments to either https://bsky.app/bruceeckel or Github Issues.
Introduction to .pyi
Stub Files#
.pyi
stub files provide type annotations for Python modules, especially useful when source code lacks annotations or is unavailable:
- Contains type definitions without actual implementations.
- Enables static type checking for third-party libraries.
Example:
Stub files clearly document expected types, significantly improving interoperability.
Generating Stubs Automatically with stubgen
#
stubgen
is a tool included with mypy
to automatically generate stub files from existing Python code:
Installation and Basic Use#
Generates a .pyi
file with inferred annotations, saving manual effort:
Auto-generated stubs provide a starting point for type annotations.
Writing Effective Stubs Manually#
Manual stub writing is essential when automatic inference is insufficient:
Example Stub File#
Practices#
- Clearly annotate arguments and return types.
- Use ellipsis (
...
) to indicate stub implementation. - Reflect original module's behavior accurately.
Manual stub files enhance readability and ensure accurate type definitions.
Distributing and Versioning Typing Stubs#
Typing stubs can be distributed independently or alongside the original package:
Bundled with Package#
Include stubs directly in your package:
Separate Distribution#
Publish stubs as standalone packages:
Use semantic versioning aligned with the original package for clarity and compatibility:
Effective versioning ensures seamless integration and updates.
Typing Third-party Libraries without Native Annotations#
When third-party libraries lack native annotations:
Use Third-party Typing Packages#
Install existing typing packages from PyPI:
Custom Stubs#
Write custom stub files within your project:
Ignoring Missing Annotations#
Temporarily ignore missing annotations with mypy
configuration:
Using stubs significantly improves type checking for libraries without built-in annotations, maintaining robust and reliable codebases.