A Suggestion for Python Dictionary/Class

Tim Hochberg tim.hochberg at ieee.org
Sat Dec 23 02:58:56 CET 2000

"William Djaja Tjokroaminata" <billtj at y.glue.umd.edu> >:
>However, there is a fundamental difference with Python class.  The members
> are implemented using dictionary.  The danger with dictionary is, even
> though a key does not exist, we still can make an assignment to it.  When
> we make some typo, this can be hard to debug.  For example:

Several people have suggested using a custom __setattr__ to prevent
modifying the class dictionary. Personally I think this is not normally
worth the hassle, but I think the following is a fun variation on the
__setattr__ anyway. It has the added twist of checking type, although that
could easily be disabled.


import types

class Typed:

    def __setattr__(self, key, value):
        if not hasattr(self.__class__, key):
            raise KeyError("can not set %s" % key)
        if type(value) != getattr(self.__class__, key):
            raise ValueError("%s must be of type %s" % (key,
getattr(self.__class__, key)))
        self.__dict__[key] = value

class MyTypedClass(Typed):

    anInt = types.IntType
    aFloat = types.FloatType
    aString = types.StringType
    aTuple = types.TupleType

m = MyTypedClass()

m.anInt = 5
m.aFloat = 5.0
m.aString = "five"
m.aTuple = (1,2,3,4,5)
try: m.somethingElse = 5
except StandardError, err: print err
try: m.anInt = 5.0
except StandardError, err: print err

More information about the Python-list mailing list