Skip to content

Instantly share code, notes, and snippets.

@bsolomon1124
Created August 4, 2020 17:40
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bsolomon1124/44f77ed2f15062c614ef6e102bc683a5 to your computer and use it in GitHub Desktop.
Save bsolomon1124/44f77ed2f15062c614ef6e102bc683a5 to your computer and use it in GitHub Desktop.
Easy way to deprecate arguments with argparse
import argparse
import warnings
class DeprecateAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
warnings.warn("Argument %s is deprecated and is *ignored*." % self.option_strings)
delattr(namespace, self.dest)
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--foo", action="store_true")
parser.add_argument("-b", "--bar", type=int, action=DeprecateAction, help="just a good old int")
parser.add_argument("-c", "--choo")
def mark_deprecated_help_strings(parser, prefix="DEPRECATED"):
for action in parser._actions:
if isinstance(action, DeprecateAction):
h = action.help
if h is None:
action.help = prefix
else:
action.help = prefix + ": " + h
mark_deprecated_help_strings(parser)
args = parser.parse_args()
print(args) # Namespace(x=y, ...)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment