circular dependency between class and its metaclass

Michele Simionato michele.simionato at poste.it
Mon Jan 19 03:02:12 EST 2004


Stefan Seefeld <seefeld at sympatico.ca> wrote in message news:<mailman.478.1074452823.12720.python-list at python.org>...
> hi there,
> 
> I'v run into a little problem for which I only found an ugly workaround,
> so I'd like to know whether people are aware of better ways to achieve this...
> 
> I'm defining a class 'Class' for which I want to set up a __metaclass__ 'Type'
> which does some work on class variables. In particular, it should apply
> a function on all base classes that are themself derived from 'Class'.
> 
> My first try was:
> 
> ====
> 
> class Class(object):
> 
>      class Type(type):
> 
>          def __init__(cls, name, bases, dict):
> 
>              hierarchy = list(filter(lambda i:issubclass(i, Class), bases))
>              # do something with the hierarchy here
> 
>      __metaclass__ = Type

If "i" is a subclass of Class, then it is an instance of Type: this means
that you can write

class Type(type):
    def __init__(cls, name, bases, dict):
        hierarchy = [i for i in bases if isinstance(i, Type)]
        # I like list comprehension...
 
class Class(object):
     __metaclass__ = Type

Is this nice enough for you?

     Michele Simionato



More information about the Python-list mailing list