Catching errors in attribute names at assigment

Pawel Kraszewski pawel_Kraszewski at
Mon Jun 21 22:01:31 CEST 2004

Thomas Philips wrote:

> If one makes a typographical error when assigning a value to an
> attribute (i.e if one types ClassName.xyc = 10 instead of
>, a new attribute xyc will be created, and the error
> can later prove difficult to debug.

> Is there a way to check assignments when they are made and to allow
> only those that modify a restricted set of allowable attributes?
> Looking through ClassName.__dict__.keys() is perhaps one way to
> achieve this: Is there a simpler (i.e. more Pythonic) way to do it as
> well?

Yes, there are at least two ways

 The "new" way is to use "new classes" - ones being children of "object"
class - where you have a special attribute __all__ . 

If you say __all__=["a","b","c"], those 3 attributes are the only ones valid
for field/method accessing. So class.a=5 is ok, but class.d=5 raises

The "old" way is to override __getattr__ and __setattr__ and check for a
valid name before accessing.

 Pawel Kraszewski                                FreeBSD/Linux

        E-Mail/Jabber             Phone         ICQ       GG
   Pawel_Kraszewski at    +48 604 777447   45615564   69381

More information about the Python-list mailing list