Re: python object model

scharf@EMBL-Heidelberg.DE
Tue, 30 Aug 1994 15:40:52 +0100

Guido van Rossum writes:
> I have some efficiency worries, but basically I agree with what the
> semantics you propose: __getattr__ is called only when the normal way
> of getting the attribute fails, but __setattr__ and __delattr__ are
> called immediately if they exist, instead of the normal way.
>
> One example of efficiency loss: instance_repr looks if __repr__
> exists; if it doesn't, this will try to look up __getattr__. The
> other example you have already pointed out: each call to
> instance_setattr tests for the existance of __setattr__ in the class.
> There are many similar ones. Unfortunately a class attr lookup isn't
> necessarily cheap: it has to walk the entire dependency tree, looking
> in each base class's dictionary.

> I have the following proposal for speeding up things. We can safely
> assume that the __getattr__ etc. methods are "static", i.e. they are
> defined in the class definition and the class owner or user won't try
> to change the class attribute after the class has been defined. (Even
> though for other attributes this is allowed and sometimes useful, we
> don't lose much functionality if we forbit it in this case.)

> Therefore it would be sufficiently to do the lookup of __getattr__
> (etc.) only once: when the class object is created. The class struct
> can easily contain three new fields to store these function pointers.

I agree! I also thought to make __setattr__/__getattr__ that way, but then I
would have had to modify more of python which I didn't want..

> Also note that __setslot__ etc. can be written in Python, using
> __dict__:
>
> class C:
>
> def __getslot__(self, name):
> return self.__dict__[name]
>
> def __setslot__(self, name, value):
> self.__dict__[name] = value
>
> def __delslot__(self, name):
> del self.__dict__[name]
>
> def __hasslot__(self, name):
> return self.__dict__.has_key(name)
>
> Well, this doesn't have the same semantics for getslot and hasslot if
> the attribute is defined in the class instead of in the instance, but
> that's not normally what you need I suppose -- in fact I like these
> semantics better (would it affect any of our examples?)

You are right. I just forgot, that one can modify self by using
self.__dict__. It would break some of my examples - but I don't care :-).

Michael