Strange metaclass behaviour

Michele Simionato michele.simionato at
Fri Mar 24 09:25:32 CET 2006

> After 5 years of Python, I still find it impressive how much
> vodoo and mojo one can do here :-)

True ;)

However, I should point out that I never use this stuff in production
I have found out that for my typical usages metaclasses are too much:
a class decorator would be enough and much less fragile. At the
present, we
do not have class decorators, but we can nearly fake them with a very

def thisclass(proc, *args, **kw):
   """ Example:
   >>> def register(cls): print 'registered'
   >>> class C:
   ...    thisclass(register)
   # basic idea stolen from zope.interface, which credits P.J. Eby
   frame = sys._getframe(1)
   assert '__module__' in frame.f_locals # inside a class statement
   def makecls(name, bases, dic):
         cls = type(name, bases, dic)
      except TypeError, e:
         if "can't have only classic bases" in str(e):
            cls = type(name, bases + (object,), dic)
         else: # other strange errors, such as __slots__ conflicts, etc
      del cls.__metaclass__
      proc(cls, *args, **kw)
      return cls
   frame.f_locals["__metaclass__"] = makecls

Figured you would like this one ;)

                  Michele Simionato

More information about the Python-list mailing list