0

I would like to know if it is a good practice to use tuples instead of separated expressions in a if statement.

is_dog = True
is_brown = False

I would like to do like this:

if (is_dog, is_brown):
    do_something()

Instead of like this:

if is_dog or is_brown:
    do_something()

What is the best practice in this case? Thank you

may
  • 1,073
  • 4
  • 14
  • 31
  • 1
    I don't understand, even both `is_dog` and `is_cat` is True, `if (is_cat, is_dog):` will be True`if (is_cat, is_dog):` not equals to `if is_dog or is_cat:` – recnac Apr 07 '19 at 13:07
  • 1
    You want to take a look at `any` and `all`: https://stackoverflow.com/questions/19389490/how-do-pythons-any-and-all-functions-work – Reut Sharabani Apr 07 '19 at 13:07

2 Answers2

4

There are a few things going on here:

You're using a tuple as the branching value for if. The truthiness of a predicate only indicates if its empty or not, and nothing about its contents:

assert bool(tuple()) is False
assert bool((False, )) is True

Second, if you know in advance the number of items in the tuple, using ors and ands is usually more readable, like you mentioned:

if is_dog or is_cat:
    do_something()

And lastly, you can use any for arbitrary number of values:

values = [is_dog, is_cat, ... more]
if any(values):
    do_something()
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
3

This is not good practice to see if either bool is True:

if (False,False):
    print("it does not do what you think it does")

Output:

it does not do what you think it does

See python truth value testing: any non empty tuple is True-thy

The correct way is:

if a or b:   
    pass

For multiples you can use any():

if any(x for x in (False, True)):
    pass   # will enter here if any part of the tuple is True
else:
    pass   # will enter here if no part of the tuple is True
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69