[Python-Dev] Summary of "dynamic attribute access" discussion

Anthony Baxter anthony at interlink.com.au
Wed Feb 14 00:55:40 CET 2007


On Wednesday 14 February 2007 07:39, Aahz wrote:
> My point is that I suspect that general objects are not used much
> with getattr/setattr.  Does anyone have evidence counter to that?
>  I think that evidence should be provided before this goes much
> further; perhaps all that's needed is education and
> documentation.

Ok. I just spent a little time looking in the top level of the 
stdlib.  I count 102 uses of 2-arg getattr. Here's what getattr() 
is used for:

Putting aside all of the stuff that does introspection of objects 
(pydoc, cgitb, copy, &c - I don't care that these have a slightly 
more verbose spelling, since writing this sort of introspection 
tool is hardly a common thing to do throughout a codebase) there's 
really only three use cases:

- Cheap inheritence, ala 
    def __getattr__(self, attr):
        return getattr(self.socket, attr)

- Method lookup by name - as I suspected, this is the #1 use case.

- Looking things up in modules - you're generally only going to do a 
  small amount of this, once per module.

The other uses of it make up a fairly small handful - and looking at 
them, there's better ways to do some of them. 

setattr is even less used. Most uses of it are for copying the 
attributes of one object en masse to another object. This can be 
encapsulated in a quickie function to do the work.

So based on this quick survey, I _strongly_ question the need for 
the new syntax. New syntax should need to vault vastly higher 
hurdles before getting into Python - it's just not possible to 
write code that's backwards compatible once you add it. I just 
don't see that this comes even close. We're already looking at a 
big discontinuity with 2.x -> 3.x in terms of compatibility, I 
think adding another for 2.5->2.6, for what I consider a marginal 
use case is VERY BAD.

Something like the attrview (or attrdict, the name I'd use) _can_ be 
done in a backwards compatible way, where people can distribute a 
workalike with their code. I doubt I'd use it, either, but it's 
there for people who need it.

I again ask for examples of other compelling uses that wouldn't be 
better solved by using a dictionary with keys rather than an object 
with attributes.

Anthony


More information about the Python-Dev mailing list