<div class="gmail_quote">On Thu, Mar 24, 2011 at 06:40, Jameson Quinn <span dir="ltr"><<a href="mailto:jameson.quinn@gmail.com">jameson.quinn@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
"class attrdict" is a perennial dead-end for intermediate pythonistas who want to save 3 characters/5 keystrokes for item access. Other languages such as javascript allow "somedict.foo" to mean the same as "somedict['foo']", so why not python? Well, there are a number of reasons why not, beginning with all the magic method names in python.<div>
<br></div><div>But saving keystrokes is still a reasonable goal.</div></blockquote><div><br></div><div>Code is read far more often than it is written, so readability tends to count more than most other metrics.</div><div>
<br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;"><div>So what about a compromise? Allow "somedict..foo", with two dots, to take that place. It still saves 2 characters (often 4 keystrokes; and I find even ', "[", or "]" harder to type than ".").</div>
</blockquote><div><br></div><div>I don't see the benefit, but maybe it'll save a few bytes in file size. Anyone reviewing your code now has to think "does this need one or two dots?"</div><div><br></div>
<div>Anyways, why not just do something like this:</div><div><br></div><div>class AttrDict(dict):</div><div> def __getattr__(self, attr):</div><div> return super(AttrDict, self).__getitem__(attr) </div><div><br>
</div><div><div>>>> d = AttrDict()</div><div>>>> d["a"] = 1</div><div>>>> d.a</div><div>1</div></div></div>