Class Decorators, Inheritence, super(), and maximum recursion

Posted by jamstooks on Stack Overflow See other posts from Stack Overflow or by jamstooks
Published on 2010-03-30T03:42:58Z Indexed on 2010/03/30 4:13 UTC
Read the original article Hit count: 518

I'm trying to figure out how to use decorators on subclasses that use super(). Since my class decorator creates another subclass a decorated class seems to prevent the use of super() when it changes the className passed to super(className, self). Below is an example:

def class_decorator(cls):
    class _DecoratedClass(cls):
        def __init__(self):
            return super(_DecoratedClass, self).__init__()
    return _DecoratedClass

class BaseClass(object):
    def __init__(self):
        print "class: %s" % self.__class__.__name__
    def print_class(self):
        print "class: %s" % self.__class__.__name__

bc = BaseClass().print_class()

class SubClass(BaseClass):
    def print_class(self):
        super(SubClass, self).print_class()

sc = SubClass().print_class()

@class_decorator
class SubClassAgain(BaseClass):
    def print_class(self):
        super(SubClassAgain, self).print_class()

sca = SubClassAgain()
# sca.print_class() # Uncomment for maximum recursion

The output should be:

class: BaseClass
class: BaseClass
class: SubClass
class: SubClass
class: _DecoratedClass
Traceback (most recent call last):
File "class_decorator_super.py", line 34, in <module>
sca.print_class()
File "class_decorator_super.py", line 31, in print_class
super(SubClassAgain, self).print_class()
...
...
RuntimeError: maximum recursion depth exceeded while calling a Python object

Does anyone know of a way to not break a subclass that uses super() when using a decorator? Ideally I'd like to reuse a class from time to time and simply decorate it w/out breaking it.

© Stack Overflow or respective owner

Related posts about python

Related posts about python-decorators