Python - Automatic Type Hinting With Monkeytype

I’ve been poking around with adding type hints to Python code automatically. Here’s my process so far:

  1. pip install MonkeyType
  2. run tests with monkeytype run instead of python
    • pytest: monkeytype run -m pytest
  3. mkdir stubs
  4. monkeytype list-modules | xargs -n1 -I{} sh -c 'monkeytype stub {} > stubs/{}.pyi'
  5. pip install pytype
  6. python move_files.py (below)
  7. mypy <code folder name>
  8. remove duplicate imports added by merge-pyi, fix import sorting issues
  9. clean up super long type hints by inlining with params

move_files.py:

"""Loop over generated .pyi (stub) files, get path to respective .py file,
then run merge-pyi to add type hints as comments."""
import os
import subprocess

for f in os.listdir('stubs'):
    print('merging:', f)
    split_filename = f.split('.')

    # create new path if necessary
    match_dir = split_filename[:-2]
    if match_dir:
        match_dir = os.path.join(*match_dir)
        os.makedirs(match_dir, exist_ok=True)

    py_path = split_filename[-2] + '.py'
    if match_dir:
        matching_file = os.path.join(match_dir, py_path)

    stub_file = os.path.join('stubs', f)
    commands = ["merge-pyi", "-i", "--as-comments", matching_file, stub_file]
    out = subprocess.run(commands, stdout=subprocess.PIPE).stdout
    print(out)

(gist)