Q: Meta-class usage

daishi google at daishi.fastmail.fm
Fri Dec 12 05:14:01 CET 2003


Hi,

I am wondering if someone could help me understand some of the
details of using metaclasses.

I am trying to use metaclasses to auto-generate some attributes
and methods in a class definition. I am attaching a simplified
example of the kind of code I am considering below, and I have
the following questions:

1. Is the code in NamedType.__new__ the "right" way to have a
class which has NamedType as its metaclass inherit from
NamedClass? Are the semantics different from if the class with
NamedType as its metaclass explicitly listed NamedClass as a
superclass in the standard way?
2. Is the try/except clause in NameType.__init__ the "right"
way to prevent KeyErrors for subclasses of classes with
NamedType as its metaclass?

Thanks in advance,
d

---
class NamedClass(object):
    def __init__(self, name):
        self.name = name

class NamedType(type):
    def __new__(mcl, name, bases, dictionary):
        bases = tuple(list(bases)+[NamedClass])
        return super(NamedType, mcl).__new__(mcl, name, bases, dictionary)
    def __init__(cls, name, bases, dictionary):
        try:
            name = dictionary['NAME']
        except KeyError:
            return
        def is_a(self):
            return self.name == name
        setattr(cls, 'is_a_'+name, is_a)
        def init(self):
            super(cls, self).__init__(name)
        setattr(cls, '__init__', init)

class PrintNamedType(NamedType):
    def __init__(cls, name, bases, dictionary):
        super(PrintNamedType, cls).__init__(name, bases, dictionary)
        def print_name(self):
            print self.name
        setattr(cls, 'print_name', print_name)

class NamedFoo:
    __metaclass__ = NamedType
    NAME = 'foo'

class SubNamedFoo(NamedFoo):
    pass

class NamedBar:
    __metaclass__ = PrintNamedType
    NAME = 'bar'




More information about the Python-list mailing list