Metaclasses and class variables

Mike C. Fletcher mcfletch at
Thu Aug 4 16:24:30 CEST 2005

Jan-Ole Esleben wrote:

>Yes, that works, but it is unfortunately not an option (at least not a
>good one).
>Is there no way to create a class variable that exists during
>definition of the class? (I cannot imagine there isn't, since
>technically it's possible and manually it can be done...)
The metaclass hook occurs *after* class definition, anything using a 
side-effect of a metaclass hook then, *must* occur after the execution 
of the metaclass hook.  At the time you want to write classvar.append 
the "class" is only a namespace, so, if you really need this feature 
you'll need to look elsewhere for at least *part* of the solution.

A global "classvar" that, when appended to, caches values until your 
metaclass is called and transfers the cache to the class should *work*, 
but egads that's ugly compared to just classvar = [] .  I guess what I'd 
ask is *why* is avoiding that single line so important.  It could be 
there's a reasonable answer, but the amount of machinery required to 
avoid it is going to be significant.

class meta( type ):
    newClassVar = []
    def __new__( cls, name, bases, dictionary ):
        dictionary[ 'classvar' ] = cls.newClassVar[:]
        del cls.newClassVar[:]
        return super( meta, cls ).__new__( cls, name, bases, dictionary )
__metaclass__ = meta
classvar = meta.newClassVar

or something along those lines...

Um, ick, but HTH,

  Mike C. Fletcher
  Designer, VR Plumber, Coder

More information about the Python-list mailing list