Skip to content

Instantly share code, notes, and snippets.

@nicoddemus
Last active October 4, 2023 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicoddemus/d5cdd31941c55302079385afcb227088 to your computer and use it in GitHub Desktop.
Save nicoddemus/d5cdd31941c55302079385afcb227088 to your computer and use it in GitHub Desktop.
Apply allow-untyped-defs
"""
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