frozendict (v0.1)

kj no.email at please.post
Fri Oct 8 10:00:17 EDT 2010


In <i8loa2$3oe$1 at reader1.panix.com> kj <no.email at please.post> writes:

>At any rate, using your [i.e. Arnaud's] suggestions in this and
>your other post, the current implementation of frozendict stands
>at:

>class frozendict(dict):
>    for method in ('__delitem__ __setitem__ clear pop popitem setdefault '
>                   'update').split():
>        exec """
>def %s(self, *a, **k):
>    cn = self.__class__.__name__
>    raise TypeError("'%%s' object is not mutable" %% cn)
>""" % method

>    def __hash__(self):
>        return hash(frozenset(self.items()))

>...which is a lot nicer!

As a side comment on my own post, this is the second time in less
than a week that I find myself having to resort to exec'ing some
code generated from a template.  This one is worse, because there's
nothing runtime-dependent about the code being exec'd.  It sticks
in my craw somehow.  It just doesn't seem quite right that at the
time of doing something as bread-and-butter as implementing a
subclass, one has to choose between explicitly writing a whole
bunch of identical methods, and exec-based hacks like what I'm
doing above.  There's got to be a "better" to tell Python: "override
all these superclass methods with this one."

Or maybe the problem here is that, in a perfect world, frozendict
would be in the standard library, as a superclass of dict lacking
all of dict's destructive methods.  :)

~kj




More information about the Python-list mailing list