An MWE:
Suppose a derived class NewDict
from dict
, and the setdefault
is overriden.
I need to use the parent dict
‘s method and keep some exception handlings from dict
‘s method, like argument numbers handling.
So after some customized code, super().setdefault(key, default)
is called.
class NewDict(dict):
def setdefault(self, key, default):
# some code checking key and default value
return super().setdefault(key, default)
new_dict = NewDict()
new_dict.setdefault('key', 'value', 'wrong_argument')
But the error message shows unwanted number of arguments that counts additional self
argument.
Traceback (most recent call last):
File "/Users/test.py", line 7, in <module>
new_dict.setdefault('key', 'value', 'wrong_argument')
TypeError: NewDict.setdefault() takes 3 positional arguments but 4 were given
Workaround
I know adding *args
works, like:
class NewDict(dict):
def setdefault(self, key, default, *args):
# some code checking key and default value
return super().setdefault(key, default, *args)
new_dict = NewDict()
new_dict.setdefault('key', 'value', 'wrong_argument')
then the message back to normal:
Traceback (most recent call last):
File "/Users/test.py", line 7, in <module>
new_dict.setdefault('key', 'value', 'wrong_argument')
File "/Users/chzh/test.py", line 4, in setdefault
return super().setdefault(key, default, *args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: setdefault expected at most 2 arguments, got 3
but it seems silly just changing argument signature for such case.
Seek for
Is there any clean and elegant way to handle such problem?