Newbie question about __getattr__ and __setattr__

Felix Thibault felixt at dicksonstreet.com
Tue Oct 12 02:06:36 EDT 1999


On 10 Oct 1999 12:12:23 +1300, "Tim Evans" <tre17 at student.canterbury.ac.nz> wrote:
> felixt at dicksonstreet.com (Felix Thibault) writes:
> 
> [snip]
> > I also wanted to be able to do this by assignment so I tried to
> > make a __setattr__ method, but if I do:
> > 
> > i[1][2][3] = 4
> > 
> > I get an exception from __getattr__. So my question is- Is there
> > a way to tell that __getattr__ is being called in an assignment, and not
> > to get a value, and is there a way to get all the keys and values at once?
> > Or is this a Bad Idea?
> > 
> > Thanks!
> > 
> > Felix
> 
> What about just storing all the nested keys as a tuple:
> 
> i[1,2,3] = 4
> 
> The dictionary key will be a tuple, which is fine as any immutable
> object can be a key.  It might not be as efficient, but if you wanted
> efficiency you would be using C, not python.
> 
> --
> Tim Evans

Hmmm...what would be the efficiency problem with this way? I tried
rewriting  __setitem__ to take the tuple and use it to build the nested
dictionary, but that messed up has_key for tuples...it would be nice
to make has_key work so it could say {'a': {'b': {'c': 'd'}}} has a key
['a']['b']['c'], but this already works for tuples...and it seems like indexing
with tuples is a standard way to do it. 

Thanks!




More information about the Python-list mailing list