[SOLVED] Is it possible to save the returned value of a function for the next time it is called?

Table of Contents

Issue

I’m writing a function that iteratively calculates an integral and for the next estimate I need the previous result.

I’m using an auxiliary variable to store the previous result and it works, but is it possible to do that inside the own function (something similar to SAVE declared variables in fortran)?

Solution

Nothing automagic, but functions in Python can have attributes. So, e.g., this works:

>>> def f(n):
...     result = n+1
...     f.last = result
...     return result
>>> f(6)
7
>>> f.last
7

Nothing magic about the name last there – just an arbitrary identifier I made up. Of course you can bind that attribute outside the function body too:

>>> f.last = 12
>>> f.last
12

Magic

If you do a lot of this (which I wouldn’t really recommend), it’s possible to automate it with a bit of code, via writing a "decorator" you can apply to functions to alter their behavior. This is quite magical:

# Decorator to change a function to save its last return value
# in attribute `last`.
from functools import wraps
def addlast(f):
    @wraps(f)
    def g(*args, **kw):
        g.last = f(*args, **kw)
        return g.last
    g.last = None
    return g

Given that, you can put "@addlast" right before a function definition to alter its behavior, without changing the function itself:

@addlast
def f(i, j):
    return i + j

print(f.last)
print(f(3, 9))
print(f.last)

which displays:

None
12
12

Answered By – Tim Peters

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *