Newbie question about __getattr__ and __setattr__

Felix Thibault felixt at dicksonstreet.com
Fri Oct 8 23:48:02 EDT 1999


I'm trying to learn Python by writing a gui for a
screen-saver program (xlock). To store the 
default settings I was using nested dictionaries,
and they seemed like they could be generally 
useful, so I ended up with this class:

from UserDict import UserDict

class Nester(UserDict):
    def __add__(self, other):
      sum =self.addentry(self.data, other)
      return Nester(sum)

    __radd__ = __add__
      

    def addentry(self, a, b):
        DualValueError =  "Dictionaries assign different values with same key"
        try:
            sum = a.copy()
            for key in b.keys():
                if sum.has_key(key) and sum[key] != b[key]:
                    sum[key] = [sum[key] , b[key]]
                    sum[key] = self.addentry(sum[key][0], sum[key][1])
                else:
                    sum[key] = b[key]
            return sum
        except AttributeError:
            raise DualValueError

which I use like this:

>>> import Dicky
>>> i =Dicky.Nester({'a': {'b': {'c': 'd'}}})
>>> i
{'a': {'b': {'c': 'd'}}}
>>> i = i+{'a':{'b':{'e':'f'}}}
>>> i
{'a': {'b': {'c': 'd', 'e': 'f'}}}
>>> 

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




More information about the Python-list mailing list