[Python-ideas] Keyword for direct pass through of kwargs to super

Michael Lohmann mial.lohmann at gmail.com
Sat May 26 05:22:39 EDT 2018


Let me put it this way:

   class A(object):
       def __init__(self, a_value, **kwargs):
           print("This is a value:", a_value)
           super().__init__(**kwargs)

Which parameters does  `A` take when being initialized?

Whenever you give any kwargs when directly instantiating `A` they will be passed down to super which in this case is `object`. And now to the follow-up question: Can you tell me which kwargs object takes as an input for it’s __init__? So does it EVER make ANY sense to specify them if you DIRECTLY create an instance of `A`?

But now let’s say your MRO is `SuperClass, A, B`, then A should better be able to forward the kwargs, so currently you need to directly hand them to `A` and rely on the fact that it passes them on to `B`. Why should `A` even get those kwargs in the first place? They could just be "passed around it" as soon as the interpreter sees that they are in the what currently would be **kwargs and later reunited with the arguments that the super().__init__ call has. Of course this can’t be done by default. So why not tell the interpreter with something like "@pass_through_kwargs" that it should do this for you?

[Chris Angelico]
> Does that make sense?
Well yes, of course it does. When instantiating a HawaiianPizza of course you want to set size and price. I don’t want to remove **kwargs and the current way of handeling this. But if you now add:
    class Lasagna:
        def __init__(self, *, number_of_layers=5):
            print("This Lasagna has %s layers", number_of_layers)

    class HaveYouEverTriedThis(Pizza, Lasagna):
        """Well, this is just bizarre"""

Now suddenly `Pizza` would have to accept kwargs. Why????????? It didn’t "learn anything new". It can’t do anything with them on it’s own. Shouldn’t you expect from a function that in the brackets you are shown what is possible to actually call this function on? You could never actually call Pizza with kwargs, so 1) Why should you be able to do so in the first place? and 2) Why show the programmer that you could?. Just to make the MRO work. And I would suggest that to handle this it would be a lot more elegant to say: "If you are in the middle of an MRO: just pass everything unexpected down“

[Steven D'Aprano]
> Considering that *I* made this example up, it is a bit rich for you to 
> tell me that "eggs" isn't used. Of course it is used, by one of the 
> superclasses. That's why it was provided.
Well, then your code should stay with the current version of accepting **kwargs and not do this. And of course you can only use one of **kwargs and this new proposal


More information about the Python-ideas mailing list