Issue 34827: Make argparse.NameSpace iterable (original) (raw)
Issue34827
Created on 2018-09-28 05:44 by bubthegreat, last changed 2022-04-11 14:59 by admin. This issue is now closed.
Messages (3) | ||
---|---|---|
msg326605 - (view) | Author: Micheal Taylor (bubthegreat) | Date: 2018-09-28 05:44 |
There was an issue to make argparse.Namespace iterable with a specific intent on being able to convert it to a dictionary (https://bugs.python.org/issue8982). Additionally there was another improvement request to make it accessible like a dictionary. (https://bugs.python.org/issue8979) While vars(args) and args.thing do accomplish the needs, I'm really lazy, and would like the object to be more accessible - for instance, if I will always need to access every attribute (because I make a small namespace that fits a simple script, making it iterable would be convenient. It's also more convenient to use the typical **thing syntax for passing it into functions if all the attributes are required for different things. This keeps code within the functions that would use it simpler, because we no longer need to reference args.thing, we can reference thing directly within the function it's been passed to. vars(args) does accomplish this, but it is arguably not as familiar for folks as the more "familiar" syntax of **args. | ||
msg326607 - (view) | Author: Serhiy Storchaka (serhiy.storchaka) * ![]() |
Date: 2018-09-28 06:08 |
is not about making argparse.Namespace iterable, it is about better documenting it. was rejected for several reasons which are still valid. For making **args working, args shouldn't be iterable, it should have the keys() method. And this will conflict with the --keys option. Python is not a JavaScript. Objects and dictionaries are different things here. If you want to convert argparse.Namespace to dict, vars(args) is the One Obvious Way. It is officially documented. | ||
msg326652 - (view) | Author: paul j3 (paul.j3) * ![]() |
Date: 2018-09-28 18:50 |
As documented in https://docs.python.org/3/library/argparse.html#the-namespace-object you can create your own 'namespace' class, that does everything you want and more. argparse makes very few assumptions about the object - using getattr, setattr, and hasattr where possible. All that the argparse.Namespace class adds to a plain object is the ability to set initial attributes, and to display them in a pretty way. Look at Namespace.__repr__ to see how it accesses its attributes. For a function with a fn(*args, **kwargs) signature, a namespace 'ns', can be passed in in 2 ways: fn(*ns._get_kwargs(), **ns.__dict__) |
History | |||
---|---|---|---|
Date | User | Action | Args |
2022-04-11 14:59:06 | admin | set | github: 79008 |
2018-09-28 18:50:44 | paul.j3 | set | nosy: + paul.j3messages: + |
2018-09-28 06:08:56 | serhiy.storchaka | set | status: open -> closednosy: + serhiy.storchakamessages: + resolution: rejectedstage: resolved |
2018-09-28 05:44:33 | bubthegreat | create |