A Suggestion for Python Dictionary/Class

Alex Martelli aleaxit at yahoo.com
Fri Dec 22 17:56:19 EST 2000


"William Djaja Tjokroaminata" <billtj at y.glue.umd.edu> wrote in message
news:920fe9$c20$1 at hecate.umd.edu...
    [snip]
> 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
    [snip]
> 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?

My opinion is that it would be nice for Python dictionaries to
provide various kinds of 'locking' options in general, but the
specific request you have is very easy to implement in today's
Python, right as it stands.

class FixedMembersMixin:
    _expando = 0
    def __setattr__(self, name, value):
        if not self._expando and not hasattr(self,name):
            raise AttributeError, name
        self.__dict__[name]=value

Just inherit your class from FixedMemberMixin: you'll be
able to set in an instance only those attributes which are
class attributes too.

For example:

class Point2d(FixedMembersMixin):
    x=y=None
    def __init__(self, x, y):
        self.x=x
        self.y=y

Now, for example:

>>> p = Point2d(1.2,3.4)
>>> print p.x
1.2
>>> p.x *= 1.1
>>> print p.x
1.32
>>> p.z = 7.8
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "tep.py", line 5, in __setattr__
    raise AttributeError, name
AttributeError: z
>>>

The mixin only lets you set instance attributes that already
are present (as either instance or class ones).  The _expando
attribute can be set to some true value to turn this off in a
temporary way, for convenience; or, you can set the
attributes explicitly via the self.__dict__[name]=value way.
Neither is a problem as I see it -- no accidents are likely!
Anyway, you don't have to have _expando unless you _wish_
to have it -- the mixin's even simpler if you omit it, of course
(down to just 5 lines, and one of them gets shorter:-).

You may choose different conventions to encode what
attributes can be set, of course.  The key point is that Python
already has all the machinery you need to get your wish,
with just a few lines' worth of a mixin class (it doesn't
have to be a mixin, that's just the handiest way to do it).


Alex






More information about the Python-list mailing list