The meaning of "="

Aahz aahz at pythoncraft.com
Tue Jul 14 11:58:30 EDT 2009


In article <m24otg3hkk.fsf at cs.uu.nl>, Piet van Oostrum  <piet at cs.uu.nl> wrote:
>>>>>> Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> (LD) wrote:
>
>>LD> In message <h3bogf$oo0$1 at panix3.panix.com>, Aahz wrote:
>
>>Aahz> class AttrDict:
>>Aahz>     def __getitem__(self, key):
>>Aahz>         return getattr(self, key)
>
>>LD> OK, let's try it:
>
>>LD> >>> c = {}
>>LD> >>> c["x"] = 3
>>LD> >>> c.x = 4   
>>LD>     Traceback (most recent call last):
>>LD>       File "<stdin>", line 1, in <module>
>>LD>     AttributeError: 'dict' object has no attribute 'x'
>>LD> >>> class AttrDict:
>>LD>     ...     def __getitem__(self, key):
>>LD>     ...         return getattr(self, key)
>>LD>     ...
>>LD> >>> c.x = 4
>>LD>     Traceback (most recent call last):
>>LD>       File "<stdin>", line 1, in <module>
>>LD>     AttributeError: 'dict' object has no attribute 'x'
>
>>LD> Nope, still doesn't work...
>
>Of course you need c = AttrDict()

Absolutely -- Lawrence really needs to learn to do his own debugging.

>And to get c.x = 4 working you also need a __setitem__. 

Nope.  You do need __setitem__ so that this works:

c['x'] = 4

>And to get c["x"] working AtrrDict should subclass dict:

Definitely not.  There's a perfectly good dict inside a regular class
instance already.  The only reason to subclass from dict is so that you
get all the dict methods for free; however, the cost is that you get
ugly bugs because of e.g.

c['update'] = 'foo'

Overally, I think it's much better/safer to explicitly pull the dict
methods you want to use.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair



More information about the Python-list mailing list