MonkeyType

23.3.0 · active · verified Thu Apr 16

MonkeyType is a Python library that automatically generates type annotations from sampled production types. It uses Python's `sys.setprofile` hook to record the types of function arguments, return values, and yield values at runtime. Based on this collected data, it can generate stub files (`.pyi`) or apply draft type annotations directly to existing Python code. The current stable version is 23.3.0, with a history of regular updates focusing on Python version compatibility and annotation accuracy.

Common errors

Warnings

Install

Imports

Quickstart

The quickstart demonstrates the typical workflow: first, run your Python code with `monkeytype run` to collect runtime type traces. Then, use `monkeytype stub` to generate a `.pyi` stub file with annotations, or `monkeytype apply` to inject the annotations directly into your Python source file.

import os

# my_module.py
def add(a, b):
    return a + b

def concatenate(s1, s2):
    return s1 + s2

# To run this module with MonkeyType tracing
if __name__ == "__main__":
    # Simulate usage to collect type traces
    add(1, 2)
    add(1.5, 2.5)
    concatenate("hello", "world")
    concatenate(["a"], ["b", "c"])

# --- Steps to run from your terminal ---
# 1. Save the above code as 'my_module.py'.
# 2. Run your module under MonkeyType to collect traces:
#    $ monkeytype run my_module.py
# 3. Generate a stub file (.pyi) from the collected traces:
#    $ monkeytype stub my_module > my_module.pyi
# 4. Or, apply type annotations directly to your source file (modifies in-place):
#    $ monkeytype apply my_module
#
# Note: Traces are stored in a SQLite database (monkeytype.sqlite3) by default.

view raw JSON →