By adding the lru_cache decorator we can tell Python to cache the result and save on computation time.
import functools
@functools.lru_cache()
def compute(x, y):
print(f"Called with {x} and {y}")
# some long computation here
return x+y
if __name__ == "__main__":
print(compute(2, 3))
print(compute(3, 4))
print(compute(2, 3))
Called with 2 and 3
5
Called with 3 and 4
7
5
from with_lru_cache import compute
def test_compute(capsys):
assert compute(2, 3) == 5
out, err = capsys.readouterr()
assert err == ''
assert out == 'Called with 2 and 3\n'
assert compute(3, 4) == 7
out, err = capsys.readouterr()
assert err == ''
assert out == 'Called with 3 and 4\n'
assert compute(2, 3) == 5
out, err = capsys.readouterr()
assert err == ''
assert out == '' # compute is not called!