Skip to content

Instantly share code, notes, and snippets.

@bsolomon1124
Created August 4, 2020 17:40
Show Gist options
  • 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, ...)
@k-bharadwaj
Copy link

Super useful! But to anyone else looking to deprecate arguments, deprecate=True is supported in argparse from Python v3.12+.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment