Using metaclasses to inherit class variables

Steven Bethard steven.bethard at gmail.com
Sat May 20 07:39:20 CEST 2006


telesphore4 at gmail.com wrote:
> 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.

getattr() does, setattr() doesn't.

> 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

Does this do what you want?  Note that I don't even bother with __dict__ 
since the class dict is already available as the final argument to __init__.

 >>> class SetClassVars(type):
...     cvars = dict(name=None, desc=None, required=True)
...     def __init__(cls, name, bases, classdict):
...         for name, value in SetClassVars.cvars.iteritems():
...             if not name in classdict:
...                 setattr(cls, name, value)
...
 >>> class C(object):
...     __metaclass__ = SetClassVars
...     name = 'foo'
...
 >>> class D(C):
...     __metaclass__ = SetClassVars
...     desc = 'bar'
...
 >>> print C.name, C.desc, C.required
foo None True
 >>> print D.name, D.desc, D.required
None bar True


STeVe



More information about the Python-list mailing list