[Tutor] Custom metaclass?

Michael Hannon jmh at physics.ucdavis.edu
Thu Apr 19 22:31:20 CEST 2007

Greetings.  I've been looking at O'Reilly's "Python Cookbook", 2nd 
edition, just for my own edification.  In particular, I'm looking at 
chapter 6, "Object-Oriented Programming".

Recipe 6.3, "Restricting Attribute Setting", intends to solve the 
problem that,  by default, users can add and modify attributes of class 
instances, or even classes themselves, as in the following example:

     >>> class Foo(object): pass
     >>> f = Foo()
     >>> f.age = 42
     >>> f.age
     >>> Foo.loc = 'Tralfamadore'
     >>> g = Foo()
     >>> g.loc

The approach, in essence, is a fairly standard one: redefine the 
__setattr__ method to add some logic to enforce whatever restrictions 
you choose, but the details are a bit convoluted.  Copyright law 
probably prohibits me from posting the entire recipe, but here's the 
piece that leads to my question (see below):

class NoNewAttrs(object):
     """ subclasses of NoNewAttrs inhibit addition of new attributes,
         while allowing existing attributed to be set to new values.
     # block the addition new attributes to instances of this class
     __setattr__ = no_new_attributes(object.__setattr__)
     class __metaclass__(type):
         "simple custom metaclass to block adding new attrs to this class"
         __setattr__ = no_new_attributes(type.__setattr__)

(Beware line breaks introduced by email software.)

Finally, my question: can somebody enlighten me as to how and why the 
"custom metaclass",

     class __metaclass__(type):

does something useful?


					- Mike
Michael Hannon            mailto:hannon at physics.ucdavis.edu
Dept. of Physics          530.752.4966
University of California  530.752.4717 FAX
Davis, CA 95616-8677

More information about the Tutor mailing list