MonkeyType collects runtime types of function arguments and return values, and can automatically generate stub files or even add draft type annotations directly to your Python code based on the types collected at runtime.
some/module.py originally contains:
def add(a, b): return a + b
from some.module import add add(1, 2)
Now we want to infer the type annotation of
MonkeyType. One way is to run:
$ monkeytype run myscript.py
By default, this will dump call traces into a SQLite database in the file
monkeytype.sqlite3 in the current working directory. You can then use the
monkeytype command to generate a stub file for a module, or apply the type
annotations directly to your code.
monkeytype stub some.module will output a stub:
def add(a: int, b: int) -> int: ...
monkeytype apply some.module will modify
def add(a: int, b: int) -> int: return a + b
This example demonstrates both the value and the limitations of
MonkeyType. With MonkeyType, it's very easy to add annotations that
reflect the concrete types you use at runtime, but those annotations may not
always match the full intended capability of the functions. For instance,
is capable of handling many more types than just integers. Similarly, MonkeyType
may generate a concrete
List annotation where an abstract
Iterable would be more appropriate. MonkeyType's annotations are an
informative first draft, to be checked and corrected by a developer.
Readability and static analysis are the primary motivations for adding type annotations to code. It's already common in many Python style guides to document the argument and return types for a function in its docstring; annotations are a standardized way to provide this documentation, which also permits static analysis by a typechecker such as mypy.
MonkeyType requires Python 3.7+ and the libcst library (for applying type stubs to code files). It generates only Python 3 type annotations (no type comments).
Install MonkeyType with pip:
pip install MonkeyType
How MonkeyType works
MonkeyType uses the sys.setprofile hook provided by Python to interpose on function calls, function returns, and generator yields, and record the types of arguments / return values / yield values.
See the full documentation for details.
Check if your issue is mentioned in the frequently asked questions list.
See CONTRIBUTING.rst for information on developing and contributing to MonkeyType.
MonkeyType is BSD licensed.