Skip to content

Instantly share code, notes, and snippets.

@AlexRiina
Last active August 23, 2020 23:02
Show Gist options
  • Save AlexRiina/3de5f1e8f5b7543793b72b1f2995c558 to your computer and use it in GitHub Desktop.
Save AlexRiina/3de5f1e8f5b7543793b72b1f2995c558 to your computer and use it in GitHub Desktop.
remove Optional[] annotation wrappers where redundant
"""
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