decorator to prevent adding attributes to class?

Michele Simionato michele.simionato at gmail.com
Fri Jul 11 11:45:27 EDT 2008


On Jul 11, 5:29 pm, Neal Becker <ndbeck... at gmail.com> 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):
http://stacktrace.it/articoli/2008/06/i-pericoli-della-programmazione-con-i-mixin1/

There is also a recipe that does exactly what you want by means of a
metaclass:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158
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):
            set(self,name,value)
        else:
            raise AttributeError("You cannot add attributes to %s" %
self)
    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."""
    __setattr__=frozen(object.__setattr__)
    class __metaclass__(type):
        __setattr__=frozen(type.__setattr__)

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