[Python-ideas] a simple namespace type
T.B.
bauertomer at gmail.com
Sun May 27 19:58:45 CEST 2012
On 2012-05-27 19:08, Sven Marnach wrote:
> Calvin Spealman schrieb am Sun, 27. May 2012, um 09:42:26 -0400:
>> - record
>> - flexobject
>> - attrobject
>> - attrdict
>> - nameddict
>> - namedobject
>
> Since the proposed type is basically an `object` allowing attributes,
> another option would be `attrobject`.
>
> Adding an `__iter__()` method, as proposed earlier in this thread,
> seems unnecessary; you can simply iterate over `vars(x)` for an
> `attrobject` instance `x`.
>
Is this whole class really necessary? As said before, this type is
implemented numerous times:
* empty class (included in the Python Tutorial) [1]
* argparse.Namespace [2]
* multiprocessing.managers.Namespace [3]
* bunch (PyPI) that inherits from dict, instead of wrapping __dict__ [4]
* many more...
Each of them has a different semantics. Each is suited for a slightly
different use case and they are so easy to implement. So you can
customize to your liking - fields can or can't begin with "_", the later
__repr__ comment or the color of the shed. Still, it seems they do not
have a "killer feature" like namedtuple's efficiency.
Noticeable is how much they resemble a dict. Some let you iterate over
the keys, test for equality and even all of the builtin dict methods
(bunch). If you already use vars() for iteration, you might want a dict.
Funny that except for the easy "class Namespace: pass", the rest fail
repr for recursive/self-referential objects:
>>> from argparse/multiprocessing.managers/simplenamespace import Namespace
>>> ns = Namespace()
>>> ns.a = ns
>>> repr(ns)
...
RuntimeError: maximum recursion depth exceeded
The next snippet use the fact that dict's __repr__ knows how to handle
recursion to solve the RuntimeError problem:
def __repr__(self):
return "{}({!r})".format(self.__class__.__name__, self.__dict__)
TB
[1] http://docs.python.org/dev/tutorial/classes.html#odds-and-ends
[2] http://hg.python.org/cpython/file/c1eab1ef9c0b/Lib/argparse.py#l1177
[3]
http://hg.python.org/cpython/file/c1eab1ef9c0b/Lib/multiprocessing/managers.py#l913
[4] http://pypi.python.org/pypi/bunch
More information about the Python-ideas
mailing list