Re: python object model

Guido.van.Rossum@cwi.nl
Mon, 29 Aug 1994 15:21:35 +0200

Thanks for your mods and copious examples! I think this is very
useful (and I was already busy implementing something similar :-).

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.

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?)

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
<URL:http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>