<div dir="ltr"><div class="gmail_quote">On Tue, May 22, 2012 at 7:26 PM, Eric Snow <span dir="ltr"><<a href="mailto:ericsnowcurrently@gmail.com" target="_blank">ericsnowcurrently@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
Below I've included a pure Python implementation of a type that I wish<br>
was a builtin.  I know others have considered similar classes in the<br>
past without any resulting change to Python, but I'd like to consider<br>
it afresh[1][2].<br>
<br>
  class SimpleNamespace:<br>
      """A simple attribute-based namespace."""<br>
      def __init__(self, **kwargs):<br>
          self.__dict__.update(kwargs)  # or self.__dict__ = kwargs<br>
      def __repr__(self):<br>
          keys = sorted(k for k in self.__dict__ if not k.startswith('_'))<br>
          content = ("{}={!r}".format(k, self.__dict__[k]) for k, v in keys)<br>
          return "{}({})".format(type(self).__name__, ", ".join(content))<br>
<br>
This is the sort of class that people implement all the time.  There's<br>
even a similar one in the argparse module, which inspired the second<br>
class below[3].  If the builtin object type were dict-based rather<br>
than slot based then this sort of namespace type would be mostly<br>
superfluous.  However, I also understand how that would add an<br>
unnecessary resource burden on _all_ objects.  So why not a new type?<br>
<br>
Nick Coghlan had this objection recently to a similar proposal[4]:<br>
<br>
    Please, no. No new<br>
    just-like-a-namedtuple-except-you-can't-iterate-over-it type, and<br>
    definitely not one exposed in the collections module.<br>
<br>
    We've been over this before: collections.namedtuple *is* the standard<br>
    library's answer for structured records. TOOWTDI, and the way we have<br>
    already chosen includes iterability as one of its expected properties.<br>
[...]</blockquote><div><br></div><div>I've implemented this a few times as well. I called it "AttributeDict" or "Record".</div><div><br></div><div><br></div><div>I think adding an __iter__ method would be beneficial. E.g.</div>
<div><br></div><div><div>class 
SimpleNamespace :</div><div>     def __init__(self, **kwargs):</div><div>         self.__dict__.update(kwargs)  # or self.__dict__ = kwargs</div><div>         self.__iter__ = lambda: iter(kwargs.keys())</div></div><div><br>
</div><div><br></div><div>Why do we need this imo:</div><div><br></div><div>* sometimes x.something feels better than x['something']</div><div>* to ease duck-typing, making mocks, etc.</div><div>* Named tuple feels clunky for certain dynamic cases (why do I need to create the type for a one-off?)</div>
<div><br></div><div><br></div><div>I wonder if SimpleNameSpace should allow __getitem__ as well...</div><div><br></div><div><br></div><div>Yuval</div><div><br></div><div><br></div></div></div>