Using metaclasses to inherit class variables
telesphore4 at gmail.com
telesphore4 at gmail.com
Sat May 20 02:57:48 EDT 2006
Hmm. setattr() only does a shallow search. Good to know.
Your
if not name in dict: setattr(cls, name, value)
is a more succinct/better way of writing
if not cls.__dict__.has_key(var): setattr(cls, var, val)
Which i tested a fair bit.
OK it appears that both are working for the simple types. However, if I
do:
>>> class SetClassVars(type):
... cvars = dict(lst=[], desc=None)
... 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
... desc = 'foo'
...
>>> class D(C):
... desc = bar
>>> C.lst.append('ccccc')
>>> D.lst.append('dddd')
>>> C.lst
['ccccc', 'dddd']
>>> D.lst
['ccccc', 'dddd']
I get the piling on behavior.
OK. So it seems to be a problem only with the mutable list. I made the
mistake of thinking that the list behavior was the same as for
non-mutables.
This must be a newbie mistake and it is probably documented somewhere.
*Ding* I'll bet it is the same one that bites newbies when they define
functions like:
def myfunc(lst=[]):
Looking for complicated problems with metaclasses when simple mistakes
about mutables are the issue. Occam wags his finger at me.
Thank you. That helped.
t4
More information about the Python-list
mailing list