Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #7435

Re: Recursion error in metaclass

From Terry Reedy <tjreedy@udel.edu>
Subject Re: Recursion error in metaclass
Date 2011-06-11 01:33 -0400
References <4df2e251$0$30002$c3e8da3$5496439d@news.astraweb.com>
Newsgroups comp.lang.python
Message-ID <mailman.124.1307770420.11593.python-list@python.org> (permalink)

Show all headers | View raw


On 6/10/2011 11:34 PM, Steven D'Aprano wrote:
> I have a metaclass in Python 3.1:
>
> class MC1(type):
>      @staticmethod
>      def get_mro(bases):
>          print('get_mro called')
>          return type('K', bases, {}).__mro__[1:]

The call to type figures out the proper metaclass from bases and 
forwards the call to that (or to its __new__ method). See 
Objects/typeobject.c in the source, or read the docs on metaclasses 
carefully. If the proper metaclass is MC1, ...


>      def __new__(cls, name, bases, dict):
>          mro = None
>          docstring = dict.get('__doc__')
>          if docstring == 'ham':
>              mro = cls.get_mro(bases)

and you unconditionally call get_mro again, to call this again...

>              dict['__doc__'] = "spam spam spam"
>          # Create the class we want, and return it.
>          K = super().__new__(cls, name, bases, dict)
>          if mro:
>              assert K.__mro__ == (K,) + mro
>          return K

you are in an endless loop.

Since uou do not pass dict to get_mro. it passes {} to type and MC1 and 
the test for docstring fails and the loop is broken and the empty class 
is discarded after getting its mro.

-- 
Terry Jan Reedy

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Recursion error in metaclass Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-06-11 03:34 +0000
  Re: Recursion error in metaclass Terry Reedy <tjreedy@udel.edu> - 2011-06-11 01:33 -0400
    Re: Recursion error in metaclass Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-06-11 11:38 +0000
      Re: Recursion error in metaclass Terry Reedy <tjreedy@udel.edu> - 2011-06-11 15:39 -0400
      Re: Recursion error in metaclass Daniel Urban <urban.dani@gmail.com> - 2011-06-11 22:51 +0200

csiph-web