[Python-Dev] @decoration of classes

Nick Coghlan ncoghlan at iinet.net.au
Thu Mar 31 02:05:51 CEST 2005

Michael Chermside wrote:
> So I'm inclined to use different tools for modifying functions and
> modifying classes because the ways you want to modify them are
> different, and decorators are "tuned" to what people normally want
> to do with functions (like simple wrapping) while metaclasses are
> "tuned" to what people normally want to do with classes (like support
> for inheritance.

The area where I can see an overlap is in those decorators which, rather than 
altering the behaviour of the function itself, serve to register it with an 
external framework of some description.

At the moment, a factory function that is actually implemented as a function can 
be registered with such a system using an @decorator. If you use the 
__new__/__init__ methods of a class as your factory, however, you need to either 
post-decorate the class or create a metaclass that performs the registration.

It would be nice if decorators that worked for any callable (like the 
registration example) could be easily used with classes as well as standard 
functions. (The adaptation PEP's adapter registry is an actual situation that 
comes to mind)

   # A decorator that does not alter its argument
   def register(callable):
     # Register the callable somewhere
     return callable

   # Decorated factory function
   def factory():

   # Post-decorated class
   class factory:

   # Metaclass
   class RegisteredType(type):
     def __init__(self, name, bases, dict):
       super(self, RegisteredType).__init__(self, name, bases, dict)

   class factory:
     __metaclass__ = RegisteredType

   # Class decorator (not currently possible)
   class factory:

PJE's example of moving the decoration near the top of the class definition 
without allowing class decoration contains an important caveat: it requires that 
the decorators be written to support doing that. Allowing class decoration means 
any appropriate decorators can be used, unmodified, to affect classes as well as 


Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia

More information about the Python-Dev mailing list