Monketype is a library to infer typing annotations from inspecting running code in python.

I tried to run the library to get typing annotations in a big python django monolith

I coupled it with running the existing tests:

monkeytype run manage.py test ...

And then output the file with

 monkeytype stub module_name.utils > u.stub

This needed to create a configuration file so it knows how to run django to create the stub

$ cat monkeytype_config.py 
# Standard Library
import os
from contextlib import contextmanager
from typing import Iterator

# 3rd-party
from monkeytype.config import DefaultConfig


class MonkeyConfig(DefaultConfig):
    @contextmanager
    def cli_context(self, command: str) -> Iterator[None]:
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
        import django

        django.setup()
        yield


CONFIG = MonkeyConfig()

Applying the typing directly did not work, and I had to run all of this inside the docker container.

Unfortunately the types were mostly a miss. Only the parameters used, no understanding of tuples with ellipsis. No protocols.

It is only helpful for obscure types that don’t come from the current codebase, and it takes roughly the same amount of time to run and check than doing it manually.


tags:#python #typing #django