Last active
April 23, 2021 03:26
-
-
Save paw-lu/6afdfb6c39359300e52b048cf7b9eae2 to your computer and use it in GitHub Desktop.
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
"""Add Optional typing to Python files.""" | |
import pathlib | |
import re | |
from pathlib import Path | |
def add_optional_typing(file: Path) -> None: | |
"""Add Optional typing to Python files.""" | |
file_contents = file.read_text() | |
missing_optional_re = re.compile(r'(\w+: )("?\S+"?)( = None)') | |
new_file_contents = re.sub( | |
missing_optional_re, | |
repl=lambda match: f"{match.group(1)}Optional[{match.group(2)}]{match.group(3)}", | |
string=file_contents, | |
) | |
file.write_text(new_file_contents) | |
def fix_double_option(file: Path) -> None: | |
"""Fix edge cases where Optional is stacked up.""" | |
file_contents = file.read_text() | |
double_option_re = re.compile(r"(Optional\[Optional\[)(.+)(\]\])") | |
new_file_contents = re.sub( | |
double_option_re, | |
repl=lambda match: f"Optional[{match.group(2)}]", | |
string=file_contents, | |
) | |
file.write_text(new_file_contents) | |
python_files = pathlib.Path(".").glob("**/*.py") | |
for file in python_files: | |
add_optional_typing(file) | |
fix_double_option(file) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment