Metaclasses and class variables

Jan-Ole Esleben esleben at
Thu Aug 4 14:45:52 CEST 2005


I am new to this list, and maybe this is a stupid question, but I
can't seem to find _any_ kind of answer anywhere.

What I want to do is the following:
I want to insert a class variable into a class upon definition and
actually use it during definition.

Manually, that is possible, e.g.:

class A:
  classvar = []

I don't want to explicitly set the variable, though. My idea was to
write the following:

class Meta(type):
  def __new__(cls, name, bases, d):
    d['classvar'] = []
    return type.__new__(cls, name, bases, d)

class Test:
  __metaclass__ = Meta


However, Python complains that the variable isn't defined; it can be
found in the class dictionary _after_ definition, though, and then it
can also be used. But where's the conceptual difference (to the manual

Thanks in advance,

More information about the Python-list mailing list