Python's super() considered super!
Duncan Booth
duncan.booth at invalid.invalid
Fri May 27 06:53:13 EDT 2011
Steven D'Aprano <steve+comp.lang.python at 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'
--
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list
mailing list