Created
August 4, 2020 17:40
-
-
Save bsolomon1124/44f77ed2f15062c614ef6e102bc683a5 to your computer and use it in GitHub Desktop.
Easy way to deprecate arguments with argparse
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
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
Super useful! But to anyone else looking to deprecate arguments,
deprecate=True
is supported in argparse from Python v3.12+.