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:
pip install MonkeyType
- run tests with
monkeytype run
instead ofpython
- pytest:
monkeytype run -m pytest
mkdir stubs
monkeytype list-modules | xargs -n1 -I{} sh -c 'monkeytype stub {} > stubs/{}.pyi'
pip install pytype
python move_files.py
(file in this gist)mypy <code folder name>
- remove duplicate imports added by merge-pyi, fix import sorting issues
- clean up super long type hints by inlining with params
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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) |