Metaclasses and class variables

Jan-Ole Esleben esleben at gmail.com
Thu Aug 4 11:53:28 EDT 2005


Thanks! It's a bit icky, yes, but I've been so wrapped up in
complicated thinking that I didn't see this. It's actually  quite an
OK solution (I need it because I have an internal representation for
method interfaces that needs to be saved somewhere without the user
having to worry about it, and without them having to set variables.
Method interfaces are class specific, and the only other thing I could
do would be to have a dictionary of classes somewhere, but as the
class itself uses its interface I can't see any really sensible way to
go about this differently).

Ole


2005/8/4, Mike C. Fletcher <mcfletch at rogers.com>:
> 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...)
> >
> >Ole
> >
> >
> 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
> 
> --
> ________________________________________________
>   Mike C. Fletcher
>   Designer, VR Plumber, Coder
>   http://www.vrplumber.com
>   http://blog.vrplumber.com
> 
>



More information about the Python-list mailing list