On Thu, May 24, 2012 at 5:59 AM, Yuval Greenfield
On Tue, May 22, 2012 at 7:26 PM, Eric Snow
wrote: Below I've included a pure Python implementation of a type that I wish was a builtin. I know others have considered similar classes in the past without any resulting change to Python, but I'd like to consider it afresh[1][2]. [...]
I've implemented this a few times as well. I called it "AttributeDict" or "Record".
I think adding an __iter__ method would be beneficial. E.g.
class SimpleNamespace : def __init__(self, **kwargs): self.__dict__.update(kwargs) # or self.__dict__ = kwargs self.__iter__ = lambda: iter(kwargs.keys())
I'd like to limit the syntactic overlap with dict as much as possible. Effectively this is just a simple but distinct facade around dict to give a namespace with attribute access. I suppose part of the question is how much of the Mapping interface would belong instead to a hypothetical Namespace interface. (I'm definitely _not_ proposing such an unnecessary extra level of abstraction). Regardless, if you want to do dict things then you can get the underlying dict using vars(ns) or ns.__dict__ on your instance. Alternately you can subclass the SimpleNamespace type to get all the extra goodies you want, as I showed with the Namespace class at the bottom of my first message.
Why do we need this imo:
* sometimes x.something feels better than x['something'] * to ease duck-typing, making mocks, etc. * Named tuple feels clunky for certain dynamic cases (why do I need to create the type for a one-off?)
Yup.
I wonder if SimpleNameSpace should allow __getitem__ as well...
Same thing: just use vars(ns) or a subclass of SimpleNamespace. -eric