2

I would like to see what function signatures mypy infers. Is there a way to export all of them for my package?

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958

2 Answers2

0

Mypy does not attempt to infer function signatures. Instead, mypy (and all PEP-484 compliant type checkers) treat the function signatures themselves as the "source of truth" and conduct all type-checking based on the available signatures.

Specifically, once a function has been (manually) assigned type hints, mypy will use that information to a) perform type checks within the function and b) make sure any other typed functions are calling that function in a type-safe way.

If you omit type signatures from a method, mypy skip checking that function entirely. You can override this behavior by calling mypy with either the --strict or --check-untyped-defs flag. Once you do so, mypy will assume that the function's parameters and return are all of type Any, the dynamic type.


If you are working on a sufficiently large codebase, it may be onerous to add type hints to all of your existing functions by hand. In that case, you can try:

  1. Performing whole-program type inference to try and infer type hints for your functions, try using pytype instead. That said, keep in mind that pytype is still very much a work-in-progress. Whole-program type inference is a far more challenging problem to solve vs the more local type inference PEP 484 type-checkers perform.

  2. Using Monkeytype or pyannotate -- these programs hook into your code at runtime and will try and infer types based on the runtime behavior of your code.

Both of these approaches should generate draft-quality type hints you can iterate on.

The mypy docs have more info about strategies for adopting mypy to larger codebases: https://mypy.readthedocs.io/en/latest/existing_code.html

Michael0x2a
  • 58,192
  • 30
  • 175
  • 224
0

.pyi files are Python interface files (see this answer). They look like this:

from typing import Any, Optional

def parallel_for(loop_function: Any, parameters: Any, nb_threads: int = ...): ...
def clip(number: Any, lowest: Optional[Any] = ..., highest: Optional[Any] = ...): ...
def consistent_shuffle(*lists: Any): ...

class Location:
    latitude: Any = ...
    longitude: Any = ...
    def __init__(self, latitude: Any, longitude: Any) -> None: ...
    @property
    def latitude(self): ...
    @latitude.setter
    def latitude(self, latitude: Any) -> None: ...
    @property
    def longitude(self): ...
    @longitude.setter
    def longitude(self, longitude: Any) -> None: ...
    def get_google_maps_link(self): ...
    def distance(self, there: Any): ...

This is exactly what I was searching. Those files can be generated with stubgen which is part of mypy.

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958