Kind of a strange question, but I stumbled upon this one while coding.
This is my code
EDIT: I added classes to make my structure clearer
class Hidden(object):
def x(self, aa, bb="John Doe"):
print aa, bb
class Open(object):
def __init__(self):
self.h = Hidden()
def y(self, a, b=None):
# get rid of this if-else-foo
if b is None:
self.h.x(a)
else:
self.h.x(a, b)
o = Open()
o.y("Hello") # > Hello John Doe
o.y("Hello", "Mister X") # > Hello Mister X
If b
is None
(not set), I want method x
to be called without the argument (using the default).
I wonder if there's a way to get rid of the if-else foo?
SOLUTION
As I can only accept one answer, I can say, that all listed solutions work.
Here's my summary for the given answers:
*args
are hard to read.if
statement remains, which I wanted to avoid.If you want to get rid of 'if' just do
self.h.x(a, [b, 'Default Value'][b is None])
ps. this works in python3.5+ and i don't care about python2.7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With