[Python-Dev] __getattr__
Guido van Rossum
guido@python.org
Tue, 18 Sep 2001 12:34:33 -0400
(Changing subject)
> > > _fields = {'encode':0,'decode':1,'reader':2,'writer':3}
> > > class CodecInfo(tuple):
> > > __dynamic__ = 0
> > > def __getattr__(self, name):
> > > try:
> > > return self[_fields[name]]
> > > except KeyError:
> > > raise AttributeError, name
> >
> > You want to change that raise statement into
> >
> > return tuple.__getattr__(self, name)
> >
> > Remember, new-style __getattr__ *replaces* the built-in getattr
> > operation
>
> Originally, I had _fields as a class attribute, and was using
> self._fields inside getattr, which caused a StackOverflow. I could not
> figure out why it wouldn't just find _fields in the class before
> invoking __getattr__...
>
> > (I'm still considering whether this is too backwards incompatible; we
> > could have two getattr hooks, one old-style and one new-style.)
>
> So far, it is not really incompatible, since it only applies to
> new-style classes. It is confusing to long-time users, so it deserves
> documentation.
It seems to be the number one point of confusion. It's also one of
the few places where you have to change your code when porting a class
to the new style -- which is otherwise very simple, either place a
``__metaclass__ = type'' line in your module or make all your base
classes derive from object.
--Guido van Rossum (home page: http://www.python.org/~guido/)