[Python-ideas] Required to call superclass __init__

Neil Toronto ntoronto at cs.byu.edu
Tue Nov 13 08:23:40 CET 2007


I'm not talking about having the runtime call the superclass __init__ 
for you, as I am aware of the arguments over it and I am against it 
myself. I'm talking about checking whether it's been called within a 
subclass's own __init__.

There are many kinds of objects with such complex underpinnings or 
initialization that leaving out the call to superclass __init__ would be 
disastrous. There are two situations I can think of where enforcing its 
invocation could be useful: a corporate environment and a teaching 
environment. (I've done the former and I'm working in the latter.)

If someone forgets to call a superclass __init__, problems may not show 
up until much later. Even if they do show up immediately, it's almost 
never obvious what the real problem is, especially to someone who is new 
to programming or is working on someone else's code.

I've got a working prototype metaclass and class instance 
(require_super) and decorator (super_required). Decorating a 
require_super method with @super_required will require any subclass 
override to call its superclass method, or it throws a TypeError upon 
exiting the subclass method. Here's how it works on the __init__ problem:

class A(require_super):
     @super_required
     def __init__(self):
         pass

a = A()  # No problem


class B(A):
     def __init__(self):
         super(B, self).__init__()

b = B()  # No problem


class C(B):
     def __init__(self):
         pass  # this could be a problem

c = C()  # TypeError: C.__init__: no super call


class D(C):
     def __init__(self):
         super(D, self).__init__()

d = D()  # TypeError: C.__init__: no super call


As long as A.__init__ is eventually called, it doesn't raise a TypeError.

There's not much magic involved (as metaclasses go), just explicit and 
implicit method wrappers, and no crufty-looking magic words in the 
subclasses. Not calling the superclass method results in immediate 
runtime feedback. I've tested this on a medium-small, real-life 
single-inheritance hierarchy and it seems to work just fine. (I *think* 
it should work with multiple inheritance.)

Two questions:

1. Is the original problem (missed superclass method calls) big enough 
to warrant language, runtime, or library support for a similar solution?

2. Does anybody but me think this is a great idea?

Neil




More information about the Python-ideas mailing list