Metaclasses

Robert Brewer fumanchu at amor.org
Wed Dec 22 12:01:26 EST 2004


Bob Cowdery wrote:
 
> I am trying to build a capability based API. That is,
> an instance of the api will reflect the capabilities
> of some underlying services. I could have several
> different instances of the api concurrently running
> against different back end services. A ui applet will
> bind to an api instance. I want to make this easy to
> use from the ui perspective so I envisage exposing a
> number of properties as the variable part can be
> represented by properties. I want a property to exist
> only if a capability is available so it is easily tested.
> I have tried using Property and Metaclasses to do this
> and although both work I can't figure out how to make
> multiple different instances as both get executed on
> 'import' and thus only one instance can be created.
> Inside the metaclass I have to get hold of the capability
> map I want to build the instance against. The only way I
> can see to do this at the moment is to have a metaclass
> for each capability type and hardcode the type inside it,
> then pick the appropriate metaclass when I build the
> implementation class.
 
I was with you until the last couple of sentences. :) I *think* you're trying to write something like this:

class MetaAPI(type):
    def __init__(cls, name, bases, dct):
        for name, method in capabilities.iteritems():
            setattr(cls, name, method)

class API(object):
    __metaclass__ = MetaAPI

...where all capable behaviors are attached to the API _class_.

But then you start talking about "instances", and I'm not sure whether you mean instances of the API class or not, because the metaclass doesn't have much to do with that. If you want to conditionally attach methods to instances of API, then just do it in API.__init__():

class API(object):
    def __init__(self, keyring):
        for name, method in capabilities(keyring).iteritems():
            setattr(self, name, method)

Can you show us some code? <:)


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list