Last active
August 23, 2020 23:02
-
-
Save AlexRiina/3de5f1e8f5b7543793b72b1f2995c558 to your computer and use it in GitHub Desktop.
remove Optional[] annotation wrappers where redundant
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
""" | |
Optional[] is implied in arguments when the default value is None. Leaving it | |
out is a matter of personal preference and I prefer to leave it out in favor of | |
shorter lines with not obvious behavior. | |
This script removes unnecessary Optional declarations in arguments. | |
WARNING: this updates files in-place. | |
""" | |
import redbaron | |
import argparse | |
def remove_redundant_optional(source): | |
for node in source.find_all( | |
'DefArgumentNode', | |
value=lambda v: v and v.value == 'None', | |
annotation=lambda a: a and a.name.value == "Optional" | |
): | |
node.annotation = node.annotation.getitemnode.value | |
def main(filename): | |
with open(filename, 'r') as file: | |
source = redbaron.RedBaron(file.read()) | |
remove_redundant_optional(source) | |
with open(filename, 'w') as file: | |
file.write(source.dumps()) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(__doc__) | |
parser.add_argument("filename") | |
args = parser.parse_args() | |
main(args.filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment