Paul's Programming Notes     Archive     Feed     Github

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
  3. pytest: monkeytype run -m pytest
  4. mkdir stubs
  5. monkeytype list-modules | xargs -n1 -I{} sh -c 'monkeytype stub {} > stubs/{}.pyi'
  6. pip install pytype
  7. python move_files.py (file in this gist)
  8. mypy <code folder name>
  9. remove duplicate imports added by merge-pyi, fix import sorting issues
  10. clean up super long type hints by inlining with params
"""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)
view raw move_files.py hosted with ❤ by GitHub