On Sun, Aug 10, 2003 at 11:36:05AM +0200, Jan Weil wrote:
> Did you try this code?

Are you suggesting I don't test my code submissions? :o)

No; I don't have PyGTK2 available on my network.

> The problem is that if you assign to __properties in __init__, 
> __setattr__ is called which calls __getattr__ in the if clause but 
> __properties isn't set yet --> recursion
> Therefor you have to treat the internal properties list attribute in a 
> special manner and that's why I couldn't hide it (__*).

Yeah, my bad. Just do it a tiny bit differently:

> Christian Reis kiko at async.com.br wrote:
> > You could get away with something a bit simpler even:
> >
> > class MyObject:
> >     def __init__(self):
> >         if issubclass(self.__class__, gobject.GObject):
> >             self.__properties = list(gobject.list_properties(self)
> >         else:
> >             self.__properties = []

         if isinstance(self, gobject.GObject): 
             props = list(gobject.list_properties(self)
         else:
             props = []
        self.__dict__['_MyObject__properties'] = props

The name mangling needs to be done or else the lookup below will fail.

> >     def __setattr__(self, key, value):
> >         if self.__properties and key in self.__properties:
> >             self.set_property(key, value)
> >         else:
> >             self.__dict__[key] = value
> >
> >     def __getattr__(self, key):
> >         if self.__properties and key in self.__properties:
> >             return self.get_property(key)
> >         else:
> >             return self.__dict__.get(key, None)

Ah; Note that this is wrong here. You should not return None from
getattr, or all lookups on the object for non-existent attributes will
return None. This should be:

    try:
        return self.__dict__[key]
    except KeyError:
        raise AttributeError, key

See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52238

You could skip the if self.__properties there, but since setattr can
potentially be called a lot and the list of properties is long, it might
save some (potentially infinitesimal <wink>) time.

(PS: I'm not sharp on how the 'in' operator is implemented; if it's a
constant-time operation then this is silly and you can skip the
self.__properties check).

Take care,
--
Christian Reis, Senior Engineer, Async Open Source, Brazil.
http://async.com.br/~kiko/ | [+55 16] 261 2331 | NMFL
_______________________________________________
pygtk mailing list   [EMAIL PROTECTED]
http://www.daa.com.au/mailman/listinfo/pygtk
Read the PyGTK FAQ: http://www.async.com.br/faq/pygtk/

Reply via email to