My goal is to memoize the object instantiation such that there is only one object with the same initialization arguments.
I adapted some code from this post, and the following code works. Basically, memoize
is a decorator that caches the initialization arguments. Next time the same initialization arguments are used, the cached object is returned, instead of creating a new one.
from functools import wraps
def memoize(function):
memo = {}
@wraps(function)
def wrapper(*args):
if args in memo:
return memo[args]
else:
rv = function(*args)
memo[args] = rv
return rv
return wrapper
@memoize
class Test(object):
def __init__(self, v):
self.v = v
class TT(object):
def __init__(self, v):
self.t = Test(v)
tests= [Test(1), Test(2), Test(3), Test(2), Test(4)]
for test in tests:
print test.v, id(test)
tt = TT(2)
print id(tt.t)
And I got desired results
1 4355094288
2 4355094416
3 4355094544
2 4355094416
4 4355094672
4355094416
The question I have is that do I need to manually clear the cache memoize.memo
? It seems that it will contain the references and prevent memory to be released. Is there a way to make this resource release more automated?