Metaclasses

Robert Brewer fumanchu at amor.org
Wed Dec 22 15:38:18 EST 2004


Bob Cowdery wrote:
> What I want to do is when
> 
> class API(object):
>     __metaclass__ = MetaAPI
> 
> is created that MetaAPI generates attributes from a given
> capability map and not the one it picked up on 'import'.

Okay. It depends on where you're getting that capability information from, but the simplest approach I can think of would be to stick it in the class:

class API(object):
    __metaclass__ = MetaAPI
    
    capmap = global_map_getter(usercontext_or_keyring)

...then "capmap" should be available within MetaAPI.__init__:

class MetaAPI(type):
    def __init__(cls, name, bases, dct):
        for name, method in dct['capmap']:
            setattr(cls, name, method)

Of course, all of this could be done without using a metaclass--just call setattr as needed right after your class is defined. Another option would be to immediately follow your API class definition with a call like:

from myframework import captools

class API(object):
    def foo():
        pass

captools.enable(API)


...the choice comes down IMO to what you think will be the most usable/maintainable by those who follow you.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list