-2

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

kambi
  • 3,291
  • 10
  • 37
  • 58
  • Its unclear what you're asking. – Sayse Jun 11 '19 at 12:51
  • Everything you store in global objects and variables in the program persists for the lifetime of the program. Why would function attributes be any different? – Barmar Jun 11 '19 at 13:10

1 Answers1

0

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.

Kevin
  • 74,910
  • 12
  • 133
  • 166