all Python 3argparseterm
argparse.Namespace
parser
A simple attribute holder returned by parse_args(): each argument becomes an attribute, and vars() turns it into a plain dict.
Syntax
args = parser.parse_args(...); args.name; vars(args)
The attribute name comes from dest, with dashes replaced by underscores: '--max-size' is read as args.max_size, not args['max-size'] — square brackets raise TypeError, because a Namespace is not a dict. Use vars(args) to get a dict, for example to pass the arguments to a function with **. The in operator and == against another Namespace both work, and parse_args(namespace=obj) fills an object of your own.
Examples
import argparse
parser = argparse.ArgumentParser(prog='app')
parser.add_argument('--max-size', type=int)
args = parser.parse_args(['--max-size', '5'])
print(args.max_size, vars(args)) # → 5 {'max_size': 5}
print(args == argparse.Namespace(max_size=5)) # → True
import argparse
args = argparse.Namespace(name='Anna')
try:
print(args['name'])
except TypeError as e:
print(e) # → 'Namespace' object is not subscriptable
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy