Duncan Booth wrote:
Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote:

I was thrilled to learn a new trick, popping keyword arguments before calling super, and wondered why I hadn't thought of that myself. How on earth did I fail to realise that a kwarg dict was mutable and therefore you can remove keyword args, or inject new ones in?

Probably because most of the time it is better to avoid mutating kwargs. Instead of popping an argument you simply declare it as a named argument in the method signature. Instead of injecting new ones you can pass them as named arguments.


def foo(x=None, **kwargs):
        bar(y=2, **kwargs)

        
def bar(**kwargs):
        print(kwargs)

foo(x=1, z=3)
{'y': 2, 'z': 3}
foo(x=1, y=2, z=3)
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    foo(x=1, y=2, z=3)
  File "<pyshell#4>", line 2, in foo
    bar(y=2, **kwargs)
TypeError: bar() got multiple values for keyword argument 'y'

And the above error is exactly why you don't want to use named arguments in MI -- because you don't know in what order the methods will be called, you cannot know which named arguments to supply to the method that super() will call next.

~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to