function attribute lifespan

118 Views Asked by At

I'm writing a memoization of a function and I want to store an attribute in the function object. Will the function attribute be available for the lifespan of the process? if not how can I achieve such a thing?

Thank you

1

There are 1 best solutions below

0
Kevin On BEST ANSWER

I interpret this question as "can I reasonably expect a user-defined attribute of a function object to persist through the entire lifetime of my program? For example, in this code:

def f():
    f.x += 1
    return f.x

f.x = 0

print(f())
print(f())
print(f())

#desired result:
#1
#2
#3

... Is it guaranteed that f.x won't spontaneously lose its value halfway through?"

The x attribute of the function f will retain its value for the entire lifetime of f. Functions defined at the global scope live for the entire lifetime of the program. So you can safely use f.x for memoization.