Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I created this based on the input from this thread. I need to use odict though, so I had to override get and set attr. I think this should work for the majority of special uses.</p> <p>Usage looks like this:</p> <pre><code># Create an ordered dict normally... &gt;&gt;&gt; od = OrderedAttrDict() &gt;&gt;&gt; od["a"] = 1 &gt;&gt;&gt; od["b"] = 2 &gt;&gt;&gt; od OrderedAttrDict([('a', 1), ('b', 2)]) # Get and set data using attribute access... &gt;&gt;&gt; od.a 1 &gt;&gt;&gt; od.b = 20 &gt;&gt;&gt; od OrderedAttrDict([('a', 1), ('b', 20)]) # Setting a NEW attribute only creates it on the instance, not the dict... &gt;&gt;&gt; od.c = 8 &gt;&gt;&gt; od OrderedAttrDict([('a', 1), ('b', 20)]) &gt;&gt;&gt; od.c 8 </code></pre> <p>The class:</p> <pre><code>class OrderedAttrDict(odict.OrderedDict): """ Constructs an odict.OrderedDict with attribute access to data. Setting a NEW attribute only creates it on the instance, not the dict. Setting an attribute that is a key in the data will set the dict data but will not create a new instance attribute """ def __getattr__(self, attr): """ Try to get the data. If attr is not a key, fall-back and get the attr """ if self.has_key(attr): return super(OrderedAttrDict, self).__getitem__(attr) else: return super(OrderedAttrDict, self).__getattr__(attr) def __setattr__(self, attr, value): """ Try to set the data. If attr is not a key, fall-back and set the attr """ if self.has_key(attr): super(OrderedAttrDict, self).__setitem__(attr, value) else: super(OrderedAttrDict, self).__setattr__(attr, value) </code></pre> <p>This is a pretty cool pattern already mentioned in the thread, but if you just want to take a dict and convert it to an object that works with auto-complete in an IDE, etc:</p> <pre><code>class ObjectFromDict(object): def __init__(self, d): self.__dict__ = d </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload