Created
January 1, 2025 22:16
-
-
Save 0xdade/0da0862cd110952c6fef855498dfc618 to your computer and use it in GitHub Desktop.
ChatGPT-written tool to add bulk type ignores to your python projects (that way you can enforce strict type checking and slowly work away at the existing ignores). Make sure you don't have `--pretty` enabled or your mypy output won't work.
This file contains hidden or 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
import re | |
def parse_mypy_errors(error_file): # type: ignore[no-untyped-def] | |
"""Parse mypy errors and extract filename, line number, and error codes.""" | |
errors = [] | |
with open(error_file, 'r') as f: | |
for line in f: | |
match = re.match(r'(.*?):(\d+):\s*error:\s*(.*)\s+\[(.*)\]', line) | |
if match: | |
filename, lineno, message, error_code = match.groups() | |
errors.append((filename, int(lineno), error_code)) | |
return errors | |
def add_explicit_type_ignore(filename, line_number, error_code): # type: ignore[no-untyped-def] | |
"""Add a specific # type: ignore[<error-code>] to the problematic line.""" | |
with open(filename, 'r') as f: | |
lines = f.readlines() | |
if line_number - 1 < len(lines): | |
line = lines[line_number - 1] | |
if '# type: ignore' in line: | |
# Extract existing error codes | |
existing_ignore = re.search(r'# type: ignore\[(.*)\]', line) | |
if existing_ignore: | |
existing_codes = set(existing_ignore.group(1).split(', ')) | |
else: | |
existing_codes = set() | |
# Add the new error code | |
existing_codes.add(error_code) | |
# Replace with updated ignore comment | |
new_ignore_comment = f'# type: ignore[{", ".join(sorted(existing_codes))}]' | |
line = re.sub(r'# type: ignore.*', new_ignore_comment, line) | |
else: | |
# Add a new # type: ignore comment | |
line = line.rstrip() + f' # type: ignore[{error_code}]\n' | |
lines[line_number - 1] = line | |
with open(filename, 'w') as f: | |
f.writelines(lines) | |
def process_mypy_errors(error_file): # type: ignore[no-untyped-def] | |
"""Process mypy error file and add type ignores to offending lines.""" | |
errors = parse_mypy_errors(error_file) | |
for filename, line_number, error_code in errors: | |
try: | |
add_explicit_type_ignore(filename, line_number, error_code) | |
except Exception as e: | |
print(f"Failed to process {filename}:{line_number} - {e}") | |
if __name__ == "__main__": | |
process_mypy_errors("mypy_errors.txt") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment