all Python 3argparseterm
argparse.Action
actions
The base class for argparse actions: it decides what to do with an argument's value. Subclass it and override __call__ to define custom behaviour.
Syntax
class MyAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None): ...
Built-in actions are named by string: action='store_true', 'append', 'count'; a custom class is passed to action= as the class itself, without parentheses. In __call__(parser, namespace, values, option_string) you must store the value yourself with setattr(namespace, self.dest, ...), or the attribute keeps its default. The action runs only when the argument appears on the command line: the default never goes through __call__. And the 'append' trap: default=['a'] is extended, not replaced.
Examples
import argparse
class Upper(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, values.upper())
parser = argparse.ArgumentParser(prog='app')
parser.add_argument('--name', action=Upper, default='anon')
print(parser.parse_args(['--name', 'bob'])) # → Namespace(name='BOB')
print(parser.parse_args([])) # → Namespace(name='anon') — default не проходит через __call__
import argparse
parser = argparse.ArgumentParser(prog='app')
parser.add_argument('--file', action='append', default=['a'])
print(parser.parse_args(['--file', 'b'])) # → Namespace(file=['a', 'b'])
See also
Open in the full glossarydocs.python.orgReport an inaccuracy