How to get MRO in __new__() of metaclasses?

Michael Hudson mwh at python.net
Mon Dec 9 08:34:02 EST 2002


fvondelft at syrrx.com (Frank von Delft) writes:

> Hi all
> 
> Metaclasses rock!  One thing I didn't manage to find, however:  is
> there an easy way to retrieve the MRO of the about-to-be-created class
> while one is still mucking about in the __new__() method of its
> metaclass?

Muck about in the .mro() method instead?

/>> class M(type):
|..  def mro(self):
|..   r = super(M, self).mro()
|..   print r
|..   return r
\__ 
/>> class C:
|..  __metaclass__ = M
\__ 
[<class '__main__.C'>, <type 'object'>]


> Most metaclasses seem to have the form:
> 
> #-------------------------------------------
> class SomeMetaclass(type):
>    def __new__(cls,name,bases,dict):
>       # ... do stuff to dict ... #
>       return type.__new__(cls,name,bases,dict)
> #-------------------------------------------
> 
> i.e., while still in __new__(), the new class (name) has not yet been
> created, so its __mro__ attribute is obviously not available.  Is
> there an easy way to get it, though, short of reimplementing the mro
> algorithm?

Don't think so.

> I also tried doing my thang in __init__() instead, i.e. when the class
> *has* been created and __mro__ therefore is available, but it seems
> (??) not possible to change the __dict__ anymore once the class is
> created.  (At least, I think that's what the errors were trying to
> tell me...)

You can't change the mro after it's been set, certainly.

> Any tips will be hugely appreciated.

Explaining what you're trying to acheive may (no promises :) help us
give better answers.

Cheers,
M.

-- 
  ZAPHOD:  OK, so ten out of ten for style, but minus several million
           for good thinking, eh?
                    -- The Hitch-Hikers Guide to the Galaxy, Episode 2



More information about the Python-list mailing list