Skip to content

Run mypy programmatically on entire files (was #2369) #10810

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
edreamleo opened this issue Jul 12, 2021 · 2 comments
Closed

Run mypy programmatically on entire files (was #2369) #10810

edreamleo opened this issue Jul 12, 2021 · 2 comments

Comments

@edreamleo
Copy link

edreamleo commented Jul 12, 2021

Documentation

mypy issue #2369 was closed because, indeed, it does not make sense to run mypy on code fragments.

However, it does make sense for an IDE such as Leo to run mypy programmatically on entire files. This is far from easy, at least on Windows. For example, supposing that a mypy.bat file exists, one can not simply use subprocess.Popen to run mypy.bat. Somehow the output from mypy.bat will be swallowed. Instead, it looks like subprocess.run is required.

The following tested script finds and runs python/scripts/mypy.exe and captures the result. As you can see, the script is immune from changes to mypy's internal API. Small changes will be needed on linux, MacOS.

import os
import subprocess
import sys
#
# Change directory as needed.
directory = # <path to program under test, in this case, launchLeo.py>
os.chdir(directory)
#
# Compute path to Python/Scripts/mypy.exe.
python_dir = os.path.dirname(sys.executable)
scripts_dir = os.path.join(python_dir, 'Scripts')
mypy_exe = os.path.join(scripts_dir, 'mypy.exe')
#
# Run mypy.exe with arguments.
command = [
    mypy_exe,
    '--disable-error-code=attr-defined',
    'launchLeo.py'
]
result = subprocess.run(command, capture_output=True, universal_newlines=True)
#
# Handle the output.
for line in result.stdout.splitlines(True):
    print(line.rstrip())

It should be possible to use this script to run mypy on directories.

@emmatyping
Copy link
Member

mypy.api.run is the best way to call mypy in this manner. See the docs here: https://mypy.readthedocs.io/en/stable/extending_mypy.html

@edreamleo
Copy link
Author

@ethanhs Great! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants