iamauser
iamauser

Reputation: 11469

Python Boolean as argument in a function

I have a function that needs input as True/False that will be fed in from another function. I would like to know what is the best practice to do this. Here is the example I am trying:

def feedBool(self, x):

    x = a_function_assigns_values_of_x(x = x)
    if x=="val1" or x == "val2" :
      inp = True
    else
      inp = False

    feedingBool(self, inp)
    return

def feedingBool(self, inp) :
    if inp :
      do_something
    else :
      dont_do_something
    return

Upvotes: 0

Views: 990

Answers (3)

Jochen Ritzel
Jochen Ritzel

Reputation: 107598

You usually put the test in a function and spell out the consequence:

def test(x):
    # aka `return x in ("val1", "val2")` but thats another story
    if x=="val1" or x == "val2" :
      res = True
    else
      res = False    
    return res

def dostuff(inp):
    # i guess this function is supposed to do something with inp
    x = a_function_assigns_values_of_x(inp)
    if test(x):
      do_something
    else :
      dont_do_something

dostuff(inp)

Upvotes: 0

mogul
mogul

Reputation: 4553

why not just:

inp = x in ("val1", "val2")

of cause it can be compacted even more directly in the call to the next function, but that will be at the cost of some readability, imho.

Upvotes: 1

dawg
dawg

Reputation: 103744

You can do:

def feedBool(self, x):
    x = a_function_assigns_values_of_x(x = x)    
    feedingBool(self, bool(x=="val1" or x == "val2"))

Or, as pointed out in the comments:

def feedBool(self, x):
    x = a_function_assigns_values_of_x(x = x)    
    feedingBool(self, x in ("val1","val2"))

Upvotes: 1

Related Questions