Python Forum
if cond1 or cond2 or ...condN is not True
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
if cond1 or cond2 or ...condN is not True
#1
Hello,

Here is the code and the question:

t1 = addProduct1()
t2 = addProduct2()
...
t25 =  addProduct25()

if t1 or t2 or ... t25 is not True:
    assert False


How can I write the if condition in pythonic way?

I know it may look weird but we have a large suite of tests and the way that the framework is built we don't have other options for what we need right now so this would fit our needs.
Note that addProduct() returns either true either an 'errorText' . This is how it need it.

Thanks.
Reply
#2
Maybe better:

#!/usr/bin/python3
def addProduct1():
    return True

def addProduct2():
    return "error"

def addProduct3():
    return True


ts  = []
ts += [ addProduct1() ]
ts += [ addProduct2() ]
ts += [ addProduct3() ]
print(ts)

for t in ts:
    if type(t) == str:
        #print(t)
        assert False
Reply
#3
Well, it would be more pythonic not to have 25 addProduct functions. Much better is one addProduct function with a parameter that handles different products. However, it's not clear how those functions are set up, so I'm not sure what the best way to fix that is.

Testing for is True is not pythonic. Just test the thing. If it is True, the condition will trigger. Likewise, if condition is not True: should be if not condition:.

Finally, use any and all. These are built-in functions that take a sequence parameter. If one thing is True in the sequence, any returns True. If everything is True in the sequence, all returns True.

So:

if not any([addProduct(n) for n in range(1, 26)]):
    assert False
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
Thanks for your answers. I will try to change the approach a bit and I will comeback with an answer.
Reply
#5
actually if I understand correctly, you want all elements to be True, right?
so
if not all([addProduct(n) for n in range(1, 26)]):
    assert False
however it can be just

assert all([addProduct(n) for n in range(1, 26)]), 'Not all elements are Tue'
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Returning True or False vs. True or None trevorkavanaugh 6 9,234 Apr-04-2019, 08:42 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020