Metaclass vs Class factory

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Tue Oct 30 17:46:26 EDT 2007


lbolognini at gmail.com a écrit :
> Hi all,
> 
> I dare risk my brain exploding by reaching for the understanding of
> metaclasses.
> 
> At first i thought i almost got them, even if vaguely back in a corner
> of my mind, my understanding was that, as classes' class a metaclass
> would be able to return a different class based on input...
> 
> ... until i thought of factory functions and, Python considering
> classes just another first-class object, as such i started considering
> them.
> 
> So is anybody experienced in the dark side semantics of Python willing
> to explain the difference, in simple terms, between a metaclass and a
> function that returns a class?

The same as the difference between a class and a function that returns 
an instance.

One of the main use of metaclasses it to allow "postprocessing" of the 
class object - ie, to automatically add extra features to a class, 
usually based on the class definition. This is mostly useful for 
framework stuff, where it can avoids quite a lot of boilerplate. IOW, 
the 'input' of a metaclass is often the class object itself. The 
metaclass constructor (I mean the proper constructor, __new__) let you 
play with the class bases and attributes before the class object is 
instanciated, and the initializer (__init__) let you modify the class 
object after instanciation.

You can of course use the metaclass constructor as a class factory 
(which it is), but it's obviously overkill if all you need is to 
dynamically 'select' a class based on either inputs and/or environment 
(configuration, platform, whatnot).

HTH



More information about the Python-list mailing list