A Suggestion for Python Dictionary/Class

David Bolen db3l at fitlinxx.com
Fri Dec 22 20:30:20 EST 2000

William Djaja Tjokroaminata <billtj at y.glue.umd.edu> writes:

> In C/C++/Java, if a member does not exist and we try to access or assign
> it (because of some typo, perhaps), it will be caught by the compiler
> simply as syntax error.  Not so with Python class.
> Therefore, is there any way for me to define a class, with some definite
> members just like in C/C++/Java, so that no new members can be defined?  I
> am trying to do it, but using some conventions, not using the Python
> language features.

One approach to handling this is to define a __setattr__ function in
your class, which will get called every time you try to set any
attribute of that object.  You can impose any sort of constraints
there that you want - for example, verifying that the attribute
already exists before permitting the assignment.

I believe there have been more elaborate posts in this vein to this
group in the past - try the "How often to problems arise ... ?" thread at:


or more specifically the post within it from Alex Martelli that
implements a Strict class that only permits changing existing attributes:


> Because Python provides a read-only list in terms of tuple, I think it
> will be nice if Python provides another class type with fixed members,
> just like a dictionary with read-only keys.  Any opinion, anyone?

Since you can implement this policy your own (and if at the class
level, permit that policy to be inherited), I'm not sure it's
something that needs to be added to the core language itself.

-- David
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \

More information about the Python-list mailing list