George
George

Reputation: 1050

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?

Upvotes: 1

Views: 110

Answers (2)

wim
wim

Reputation: 363183

The functools.lru_cache can help you sometimes:

Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments.

>>> from functools import lru_cache
>>> from time import sleep
>>> @lru_cache()
... def expensive_potato():
...     print('reticulating splines...')
...     sleep(2)
...     return 'potato'
... 
>>> expensive_potato()
reticulating splines...
'potato'
>>> expensive_potato()
'potato'

That's new in Python 3.2. Easy to write your own decorator, if you're on old Python.

If you're working with methods/attributes on a class, cached_property is useful.

Upvotes: 3

lzmartinico
lzmartinico

Reputation: 159

In some languages you are able to assign a variable as part of the condition block, but in Python that's not possible (see Can we have assignment in a condition? )

Upvotes: 0

Related Questions