Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use default argument if argument is None on python method call

Tags:

python

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:

  1. @Duncan : for me it is the nicest way to achieve what I want.
  2. @falsetru : it is also a nice approach, although I think methods with *args are hard to read.
  3. @peter-wood and @tgg : both version work and save 3 lines of code. But an if statement remains, which I wanted to avoid.
like image 211
ppasler Avatar asked Jan 19 '17 15:01

ppasler


1 Answers

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

like image 132
Thomas Anderson Avatar answered Oct 20 '22 20:10

Thomas Anderson