On Thu, May 24, 2012 at 10:17 AM, Eric Snow
On Thu, May 24, 2012 at 5:59 AM, Yuval Greenfield
wrote: 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 tend to call it "Struct(ure)" -- I guess I like C better than Pascal. :-)
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.
+1
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).
Possibly there is a (weird?) parallel with namedtuple. The end result is somewhat similar: you get to use attribute names instead of the accessor syntax (x[y]) of the underlying type. But the "feel" of the type is different, and inherits more of the underlying type (namedtuple is immutable and has a fixed set of keys, whereas the type proposed here is mutable and allows arbitrary keys as long as they look like Python names).
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.
-- --Guido van Rossum (python.org/~guido)