Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
About Article
Analyze Data
Archive
Best Practices
Better Outputs
Blog
Code Optimization
Code Quality
Command Line
Daily tips
Dashboard
Data Analysis & Manipulation
Data Engineer
Data Visualization
DataFrame
Delta Lake
DevOps
DuckDB
Environment Management
Feature Engineer
Git
Jupyter Notebook
LLM
LLM
Machine Learning
Machine Learning
Machine Learning & AI
Manage Data
MLOps
Natural Language Processing
NumPy
Pandas
Polars
PySpark
Python Tips
Python Utilities
Python Utilities
Scrape Data
SQL
Testing
Time Series
Tools
Visualization
Visualization & Reporting
Workflow & Automation
Workflow Automation

Simplifying Type Annotations with MonkeyType

Table of Contents

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

Leave a Comment

Your email address will not be published. Required fields are marked *

0
    0
    Your Cart
    Your cart is empty
    Scroll to Top

    Work with Khuyen Tran

    Work with Khuyen Tran