__getattr__ and __setattr__ troubles

François Pinard pinard at iro.umontreal.ca
Tue Jun 6 19:40:28 EDT 2000


[Reissued, after a reject from python.org.  Mailman apparently failed because
 of a disk full situation.]

Michael Hudson <mwh21 at cam.ac.uk> writes:

> Have you caused Python to crap out by infinite looping with __getattr__
> yet?

Not once!  Maybe I've been lucky.  In fact, it all goes rather well now.

> > ---------------------------------------------------------------------->
> > class See:
> >     def __getattr__(self, key):
> >         print '**', key
> >         return None
> > print See()
> > ----------------------------------------------------------------------<

> > will yield:

> > ---------------------------------------------------------------------->
> > pinard at titan:~ $ python see.py
> >  ** __str__
> > Traceback (innermost last):
> >   File "see.py", line 7, in ?
> >     print See()
> > TypeError: call of non-function (type None)
> > ----------------------------------------------------------------------<

> > * By the way, and a bit unrelated, why the space before the two asterisks?

> Probably to do with softspace.  Not sure.

It should go between printed element, not before the first one, should it not?

> > * The diagnostic would be rather cryptic, if the program was not so short.
> >   Usability studies could be driven to show that the diagnostic should
> >   rather be changed to something more informative :-).

> Your wish is my command [...]  Not sure it's a sufficiently common error
> to justify this though.  I'll send it to patches at python.org and see what
> they think of it.

I hope they will accept them.  Each and every diagnostic should be as
clear as possible, and _especially_ those diagnostics which are uncommon!

> Overriding __getattr__ is good for "oo, ain't that cool" value, but it
> is probably best to try to avoid it - if you need it, fine, but consider
> alternatives first.

Of course, a "need" is a pretty subjective matter.  We can do a great
deal with very little, and there are not many so-called needs that would
really stand scrutiny.  In my case, I have a working program already,
and implementing __getattr__ is part of an intermediary cleanup, before
attempting to move further, so to simplify code all over and gain better
maintainability.  So in a sense, I could say that I considered at least one
alternative, which is already implemented and working.  I think that the
increase in legibility is worth the slowdown, which the project can afford.

P.S. - I hope that Guido will do his best so future Python stays legible.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard








More information about the Python-list mailing list