I’m trying to extend a method with a single keyword argument while remaining impartial to the rest of the method’s signature; I just want to pass that on. Attempt 0:
class SomeSuperclass(object):
pass # in reality: some implementation for some_method
class SomeClass(SomeSuperclass):
def some_method(self, my_kwarg=42, *args, **kwargs):
super(SomeClass, self).some_method(*args, **kwargs)
do_something_interesting_with(my_kwarg)
SomeClass().some_method('arg 0', 'arg 1', some_kwargs=5, my_kwarg=8)
This does not work:
Traceback (most recent call last):
File "test.py", line 9, in <module>
SomeClass().some_method('arg 0', 'arg 1', some_kwargs=5, my_kwarg=8)
TypeError: some_method() got multiple values for keyword argument 'my_kwarg'
I fully understand why the above does not work, but I’m looking for a nice way to make it work. This is my current (ugly) workaround:
class SomeClass(SomeSuperclass):
def some_method(self, *args, **kwargs):
my_kwarg = kwargs.get('my_kwarg', 42)
if 'my_kwarg' in kwargs:
del kwargs['my_kwarg']
super(SomeClass, self).some_method(*args, **kwargs)
do_something_interesting_with(my_kwarg)
That’s 3 lines of cruft per kwarg…
I’d use
dict.pop(), like so:When run, this prints out: