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

Table of Contents


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


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)
>>> f.last

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


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

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

print(f(3, 9))

which displays:


Answered By – Tim Peters

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

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