Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse.ArgumentParser - option name starting with number?

I am trying to add an option starting with number, e.g., --3d here:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--3d", action="store_true")
args = parser.parse_args(['--3d'])
print(args)

parser works well, but args looks like this and I don't know how to get the value:

Namespace(**{'3d': True})

I've tried args.3d, args("3d"), args["3d"], args{"3d"}, etc, and none of them works.

I know I can add dest in add_argument() to work around this problem, but I still want to learn how to get the data in **{}.

like image 751
Antares Avatar asked Mar 15 '26 21:03

Antares


1 Answers

Think of

Namespace(**{'3d': True})

as a way of displaying a value whose name is not a valid attribute.

'3d' can be used as a dict key, as in vars(args)['3d'].

getattr is the general purpose accessor that argparse uses internally.

Another option is use dest to set a different name.

The things you tried were wrong because:

args.3d  # bad attribute name
args("3d")  # args is not a function
args["3d"]  # args is not a dict
args{"3d"}  # bad syntax

That ** syntax does work with creating a argparse.Namespace object, but it's not something that we normally use:

In [152]: argparse.Namespace(foo='bar')
Out[152]: Namespace(foo='bar')
In [153]: argparse.Namespace(foo='bar', **{'3d':'x'})
Out[153]: Namespace(foo='bar', **{'3d': 'x'})
In [154]: getattr(_, '3d')
Out[154]: 'x'
In [155]: vars(__)
Out[155]: {'foo': 'bar', '3d': 'x'}
In [156]: _['3d']
Out[156]: 'x'

Basically argparse returns values in a simple Namespace classed object, one that gives easy attribute access for valid names, but also lets you, the user, use messy names. But the details come down to what's valid Python.

like image 65
hpaulj Avatar answered Mar 18 '26 10:03

hpaulj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!