3

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 **{}.

4
  • 3
    getattr(args, '3d')? Commented May 10, 2021 at 16:51
  • Thanks! So **{} represents the attributes that cannot use dot notation? Commented May 10, 2021 at 17:04
  • Ah, I found the **{} is just the customized repr string of the args object. It is not a syntax. Commented May 10, 2021 at 17:11
  • 1
    foo(**{'3d': True}) is equivalent to foo(3d=True), just unpacking a dict into named arguments. The difference is that 3d=… is an illegal literal, and illegal for the same reason to use as plain args.3d. However, using a string for it and alternative methods to unpack/access it works. Commented May 10, 2021 at 17:46

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.