Simplifying Type Annotations with MonkeyType

Simplifying Type Annotations with MonkeyType

Writing type annotations manually for existing Python code can be a time-consuming task, leading many developers to skip this important step. However, omitting type annotations can reduce code readability and make it harder to catch type-related bugs through static analysis.

Fortunately, MonkeyType simplifies the process of adding type annotations by automatically generating draft annotations based on the types collected at runtime. This saves time and effort compared to manual annotation.

Example Usage


Let’s say we have two files inside the folder monkey_example: utils.py and main.py.

utils.py contains the get_mean function:

def get_mean(num1, num2):
    return (num1+num2)/2

main.py calls the get_mean function:

from utils import get_mean

get_mean(1, 3)

We can infer the type annotation of get_mean in utils.py by running main.py with MonkeyType:

monkeytype run main.py

Then, we can generate a stub file for the utils module:

monkeytype stub utils

This will output:

def get_mean(num1: int, num2: int) -> float: ...

Alternatively, we can apply the type annotations directly to the code:

monkeytype apply utils

This will modify utils.py to:

def get_mean(num1: int, num2: int) -> float:
    return (num1+num2)/2

Limitations

While MonkeyType makes it easy to add annotations, those annotations may not always match the full intended capability of the functions. For example, get_mean is capable of handling many more types than just integers. MonkeyType’s annotations are an informative first draft that are meant to be checked and corrected by a developer.

Link to MonkeyType

Search

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran