Using metaclasses to inherit class variables

telesphore4 at gmail.com telesphore4 at gmail.com
Fri May 19 23:10:09 CEST 2006


I want to inherit fresh copies of some class variables. So I set up a
metaclass and meddle with the class variables there.

Now it would be convenient to run thru a dictionary rather than
explicitly set each variable. However getattr() and setattr() are out
because they chase the variable thru the class hierarchy.

So, I read the dictionary directly with cls.__dict__.has_key(var).
Reading works but when I go to set the object's dictionary directly
with:

cls.__dict__[var] = val

I get the following error:

  File Table.py, line 10, in __init__
    if not cls.__dict__.has_key(var): cls.__dict__[var] = val
TypeError: Error when calling the metaclass bases
    object does not support item assignment

Is there an easy way around this? Or am I stuck listing out the
variables one per line?

class SetClassVars(type):
    cvars = dict(name=None, desc=None, required=True, minlen=1,
                 maxlen=25, idDown=999999999, idNext=0)
    def __init__(cls, name, bases, dict):
        if not cls.__dict__.has_key('name'):     cls.name     = None
        if not cls.__dict__.has_key('desc'):     cls.desc     = None
        if not cls.__dict__.has_key('required'): cls.required = True
        if not cls.__dict__.has_key('minlen'):   cls.minlen   = 1
        if not cls.__dict__.has_key('maxlen'):   cls.maxlen   = 25
        if not cls.__dict__.has_key('idDown'):   cls.idDown = 999999999
        if not cls.__dict__.has_key('idNext'):   cls.idNext   = 0

        # It would be more convenient to loop thru a dictionary
        #for var, val in SetClassVars.cvars.iteritems():

            # getattr() and setattr() run thru the MRO
            # which is not what I want
            #if not getattr(cls, var): setattr(cls, var, val)
            #if not cls.__dict__.has_key(var): setattr(cls, var, val)

            # Setting the dictionary directly generates an error
            #if not cls.__dict__.has_key(var): cls.__dict__[var] = val

thanks
t4




More information about the Python-list mailing list