[issue11076] Iterable argparse Namespace
Éric Araujo
report at bugs.python.org
Fri Feb 4 19:43:09 CET 2011
Éric Araujo <merwok at netwok.org> added the comment:
Nice idea indeed, thanks for the patch.
For the doc section, I’d prefer to de-emplasize the specific use case of **kwargs, in favor of mentioning dict conversion in a general way:
Converting the namespace to a dict
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Namespace objects are iterable so you can easily convert them to a
:class:`dict`::
args = parser.parse_args()
argdict = dict(args)
This makes it easy to introspect the namespace or to pass the
command-line arguments to a function taking a bunch of keyword
arguments::
somefunction(**dict(parser.parse_args()))
+ def __iter__(self):
+ return iter(self.__dict__.items())
Isn’t “return self.__dict__.items()” sufficient in 3.x?
Alternate idea: don’t implement __iter__, which is sorta too broad, and implement a method that just returns a dict.
Musing: Isn’t Namespace (technically: _AttributeHolder) very much like a named tuple? Could some code be removed by using named tuples in argparse? Note that named tuples provide a method to convert themselves to a dict, and are efficient (IIRC).
----------
nosy: +bethard, eric.araujo
stage: -> patch review
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue11076>
_______________________________________
More information about the Python-bugs-list
mailing list