Automatically loading and initialising objects from a plugins directory

Fredrik Lundh fredrik at pythonware.com
Fri Jul 25 13:50:25 CEST 2008


Dave Challis wrote:

> I'll have a look into metaclasses too, haven't stumbled upon those yet
> at all.

It's a potentially brain-exploding topic, though, so if the above 
solution works for you, you might want to leave it at that ;-)

But very briefly, a metaclass is a something that's responsible for 
creating a class, much like an ordinary class is responsible for 
creating an object.  When Python executes the following statement,

     class Spam:
         attrib = 1
         def func(self):
             pass
         # <-- end of class statement

it will create a new scope for the class content, execute the class 
body, and then, when it reaches the end, call the "metaclass" to create 
the actual class object.  The metaclass is given the requested name 
("Spam" in this case), any base classes, and a dictionary containing 
everything from the class scope ("attrib" and "func", in this case). 
The thing that's returned is assigned to the "Spam" variable.

The default metaclass ("type") just creates an ordinary class object, 
but if you replace that with your own metaclas, you can completely 
override that behaviour, or just extend it (e.g. by registering the 
subclasses in a common registry).  Like, say, this:

registry = [] # list of subclasses

class Plugin(object):
     class __metaclass__(type):
         def __init__(cls, name, bases, dict):
             type.__init__(name, bases, dict)
             registry.append((name, cls))

class SpamPlugin(Plugin):
     pass

class BaconPlugin(Plugin):
     pass

for name, cls in registry:
     if cls is not Plugin:
         print name, cls

Here, the presence of an inner __metaclass__ class (which is a subclass 
of "type") causes Python's class machinery to use that class instead of 
"type" when creating class objects for Plugin or any subclass thereof. 
The extra code in the __init__ method just all plugins to a list.

For more on this, see e.g.

http://www.python.org/download/releases/2.2/descrintro/#metaclasses

</F>




More information about the Python-list mailing list