mercredi 15 mars 2017

How to check python function output and assign it to variable without executing the function twice?

Let's say I want to do the following

def calculate_something_extremally_resource_consuming():
    # execute some api calls and make insane calculations
    if calculations_sucessfull:
        return result

meanwhile somewhere else in the project:

if calculate_something_extremally_resource_consuming():
    a = calculate_something_extremally_resource_consuming()
    etc...

This looks like the heavy function will be called twice, which is really bad. Another option I can imagine:

a = calculate_something_extremally_resource_consuming()
if a:
    etc...

Maybe there is a more elegant way?

Aucun commentaire:

Enregistrer un commentaire