Voo
Voo

Reputation: 30216

Why does `object.__init__` take no args

Why doesn't object.__init__ take *args, **kwargs as arguments? This breaks some simple code in a highly annoying manner without any upsides as far as I can see:

Say we want to make sure that all __init__'s of all parent classes are called. As long as every init follows the simple convention of calling super().__init__ this will guarantee that the whole hierarchy is run through and that exactly once (also without ever having to specify the parent specifically). The problem appears when we pass arguments along:

class Foo:
    def __init__(self, *args, **kwargs):
        print("foo-init")
        super().__init__(*args, **kwargs) # error if there are arguments!

class Bar:
    def __init__(self, *args, **kwargs):
        print("bar-init")
        super().__init__(*args, **kwargs)

class Baz(Bar, Foo):
    def __init__(self, *args, **kwargs):
        print("baz-init")
        super().__init__(*args, **kwargs)

b1 = Baz() # works
b2 = Baz("error")

What's the reasoning for this and what's the best general (! it's easily solvable in my specific case but that relies on additional knowledge of the hierarchy) workaround? The best I can see is to check whether the parent is object and in that case not give it any args.. horribly ugly that.

Upvotes: 1

Views: 356

Answers (2)

Reinstate Monica
Reinstate Monica

Reputation: 4723

Raymond Hettinger's super() considered super has some information about how to deal with this. It's in the section "Practical advice".

Upvotes: 3

BrenBarn
BrenBarn

Reputation: 251373

You can see http://bugs.python.org/issue1683368 for a discussion. Note that someone there actually asked for it to cause an error. Also see the discussion on python-dev.

Anyway, your design is rather odd. Why are you writing every single class to take unspecified *args and **kwargs? In general it's better to have methods accept the arguments they need. Accepting open-ended arguments for everything can lead to all sorts of bugs if someone mistypes a keyword name, for instance. Sometimes it's necessary, but it shouldn't be the default way of doing things.

Upvotes: 4

Related Questions