2
\$\begingroup\$

I have a var af_button which is a button on UI. It can be either selected or deselected, so in that case I have four possibilities, which I have implemented. I don't like this implementation, so what would be a more pythonic way of implementing this?

af_button = squishtest.waitForObject("{text='AF' type='QPushButton' unnamed='1' visible='1'}")
if state == 'click':
    if af_button.checked == 1:
        pass
    else:
        squishtest.clickButton(squishtest.waitForObject(af_button))
else:
    if af_button.checked == 0:
        pass
    else:
        squishtest.clickButton(squishtest.waitForObject(af_button))
\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

Why do an if: pass? Just check if the case is not true by using the not equal to operator and make the else section be the point.

if state == 'click':
    if af_button.checked != 1:
        squishtest.clickButton(squishtest.waitForObject(af_button))
else:
    if af_button.checked != 0:
        squishtest.clickButton(squishtest.waitForObject(af_button))

You could shorten this further and clearer by combining the two conditions then:

if state == 'click' and af_button.checked != 1:
    squishtest.clickButton(squishtest.waitForObject(af_button))

elif state != 'click' and af_button.checked != 0:
    squishtest.clickButton(squishtest.waitForObject(af_button))
\$\endgroup\$
0
4
\$\begingroup\$

If 0 and 1 are the only possible values of af_button.checked, you could condense this to just one if:

if (state == 'click') != af_button.checked:
    squishtest.clickButton(squishtest.waitForObject(af_button))

The parentheses are important because otherwise Python would treat this as a chained comparison. (state == 'click') evaluates to True or False, and True equals 1 and False equals 0.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.