Skip to content

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:

# math.pyi
def sqrt(x: float) -> float: ...

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#

pip install mypy
stubgen -m your_module

Generates a .pyi file with inferred annotations, saving manual effort:

# generated_example.pyi
def greet(name: str) -> str: ...

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#

# custom_module.pyi
class User:
    id: int
    name: str


def fetch_user(user_id: int) -> User: ...

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:

your_package/
├── __init__.py
└── __init__.pyi

Separate Distribution#

Publish stubs as standalone packages:

pip install types-requests

Use semantic versioning aligned with the original package for clarity and compatibility:

types-requests==2.25.1

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:

pip install types-requests

Custom Stubs#

Write custom stub files within your project:

stubs/
├── requests.pyi

Ignoring Missing Annotations#

Temporarily ignore missing annotations with mypy configuration:

[mypy-requests]
ignore_missing_imports = True

Using stubs significantly improves type checking for libraries without built-in annotations, maintaining robust and reliable codebases.