Last active
May 16, 2024 12:26
-
-
Save nicoddemus/d5cdd31941c55302079385afcb227088 to your computer and use it in GitHub Desktop.
Apply allow-untyped-defs
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
""" | |
Change the "default" flags for files in a project, so new files will require full type annotations. | |
If a file has no flags, it adds "allow-untyped-defs". | |
If a file already has "disallow-untyped-defs", that flag is removed. | |
Together with this script, one should update the mypy.ini file of a project: | |
[mypy.app.*] | |
disallow_untyped_defs = true | |
""" | |
import os | |
from argparse import ArgumentParser | |
from pathlib import Path | |
def main() -> None: | |
parser = ArgumentParser(description="Add/remove mypy flags to .py files") | |
parser.add_argument('directory', help='Directory to search for Python files') | |
ns = parser.parse_args() | |
for dirpath, dirnames, filenames in os.walk(ns.directory): | |
dirpath = Path(dirpath) | |
for filename in filenames: | |
p = dirpath / filename | |
if not p.is_file() or p.suffix != '.py': | |
continue | |
lines = p.read_bytes().splitlines(keepends=True) | |
if lines: | |
first = lines[0] | |
op = None | |
if b"# mypy: disallow-untyped-defs" in first: | |
op = "removed" | |
del lines[0] | |
elif b"# mypy: allow-untyped-defs" not in first: | |
eol = first[-1:] | |
op = "added" | |
lines.insert(0, b"# mypy: allow-untyped-defs" + eol) | |
if op is not None: | |
p.write_bytes(b"".join(lines)) | |
print(f"{op}: {p}") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment