1

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?

George
  • 988
  • 2
  • 10
  • 25

2 Answers2

3

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.

wim
  • 338,267
  • 99
  • 616
  • 750
0

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? )

Community
  • 1
  • 1
lzmartinico
  • 159
  • 7