Python Forum

Full Version: if cond1 or cond2 or ...condN is not True
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
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
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
Thanks for your answers. I will try to change the approach a bit and I will comeback with an answer.
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'