How to make ** kwargs optional
I have two classes that have a method with the same name, but this method uses different parameters. So I thought about using it **kwargs
(see example below). But one of the two methods doesn't require any parameter, so I get this error:
TypeError: print_smt () takes 1 positional argument, but 2 are given
because it passes an empty dictionary into the function I suppose.
How can I solve this problem? Am I forced to use operator if
to call a function with or without parameters, or is there a better way to solve the problem?
class Bar(object):
def print_smt(self, text):
print(text)
class Foo(object):
def print_smt(self):
print("Nothing")
def test(obj, **p2):
obj.print_smt(p2)
bar = Bar()
test(bar, text='print this')
foo = Foo()
test(foo) # This one breaks!
source to share
When you call:
def test(obj, **p2):
obj.print_smt(p2)
... you are passing the dictionary print_smt()
... Even if it is an empty dictionary, it is still a dictionary, and you cannot pass a dictionary as an argument to something that takes no arguments.
If you want to pass keyword arguments as keyword arguments, rather than as a single positional argument with a dictionary, do this:
def test(obj, **p2):
obj.print_smt(**p2)
source to share