decorator to prevent adding attributes to class?

Michele Simionato michele.simionato at
Fri Jul 11 17:45:27 CEST 2008

On Jul 11, 5:29 pm, Neal Becker <ndbeck... at> wrote:
> After spending the morning debugging where I had misspelled the name of an
> attribute (thus adding a new attr instead of updating an existing one), I
> would like a way to decorate a class so that attributes cannot be (easily)
> added.
> I guess class decorators are not available yet (pep 3129), but probably
> inheritance can be used.
> Can anyone suggest an implementation?

This article could give you same idea (it is doing the opposite,
warning you
if an attribute is overridden):

There is also a recipe that does exactly what you want by means of a
It is so short I can write it down here:
# requires Python 2.2+

def frozen(set):
    "Raise an error when trying to set an undeclared name."
    def set_attr(self,name,value):
        if hasattr(self,name):
            raise AttributeError("You cannot add attributes to %s" %
    return set_attr

class Frozen(object):
    """Subclasses of Frozen are frozen, i.e. it is impossibile to add
     new attributes to them and their instances."""
    class __metaclass__(type):

Of course using frozen classes is not Pythonic at all, and I wrote the
recipe as
a proof of concept, not to use it.

   Michele Simionato

More information about the Python-list mailing list