mardi 1 décembre 2020

Python: using a function that returns two items in an If statement, without executing twice

I have a function I'm using to test in an if/then.

The issue is that I'm executing the function BOTH in the if conditional, and then again after the if statement because the function returns two items.

This just seems wasteful and I'm trying to think of ways to improve this. Here's a really basic version of what I'm trying to avoid: "True" is returned to allow the condition to pass, but then then "coolstuff()" is executed again to get more information from the function.

"coolstuff()" could possibly return false, so I can't use the returned string "stuff" as the test.

def coolstuff():
    return True, "stuff"
    
if coolstuff()[0]:
    coolthing = coolstuff()[1]
    print coolthing

There's gotta be a better way to do this, no? My brain is melting a little as I try to hash it out.

I basically want to do something like this (invalid) syntax:

def coolstuff():
    return True, "stuff"
    
if a, b == coolstuff() and a:
    print b

Aucun commentaire:

Enregistrer un commentaire