2

I have a library wich maps some REST api to some object model. So it's easy to work with the API. The problem is that every time I get some attribute of an object the library makes actual request to the server. That's not good from the performance view point.

What I want is to add functionality of memorizing the values of attributes for a some time (let say 5 min), and make the actual request only if the data is expired.

The question is that possible to do without actually changing the library's code? For example using decorators or something like that.

lesmana
  • 22,750
  • 8
  • 73
  • 83
kmelnikov
  • 43
  • 5
  • possible duplicate of [What is memoization and how can I use it in Python?](http://stackoverflow.com/questions/1988804/what-is-memoization-and-how-can-i-use-it-in-python) – lesmana Dec 15 '12 at 14:24

1 Answers1

1

You want to use the technique called 'memoizing'; my 10s Google search gives me another SO link, What is memoization and how can I use it in Python?

factorial_memo = {}
def factorial(k):
    if k < 2: return 1
    if not k in factorial_memo:
        factorial_memo[k] = k * factorial(k-1)
    return factorial_memo[k]

However you donot check for membership in the line

if not k in factorial_memo:

and you need a timeout handler -

if (curr - prev) < fiveMin
    # access Memo
else
    # start thread to get new data

HTH

Community
  • 1
  • 1
Arcturus
  • 540
  • 2
  • 6