Skip to content

Instantly share code, notes, and snippets.

@thomasballinger
Created August 20, 2013 18:40
Show Gist options
  • Save thomasballinger/6285452 to your computer and use it in GitHub Desktop.
Save thomasballinger/6285452 to your computer and use it in GitHub Desktop.
Caching, overloading __getitem__ etc, memoization
import pickle
import glob
cache = {}
def fib(x):
if x in cache:
return cache[x]
if x < 2: return 1
r = fib(x-1) + fib(x-2)
cache[x] = r
return r
print fib(32)
class LessMemoryDict(object):
def __init__(self):
pass
def __getitem__(self, item):
print 'getting item', item
try:
with open('lmd_'+item, 'r') as f:
return pickle.load(f)
except IOError:
raise KeyError
def __setitem__(self, item, value):
print 'setting item', item, 'to', value
with open('lmd_'+item, 'w') as f:
pickle.dump(value, f)
def __repr__(self):
return repr("<LessMemoryDict object with stuff that would take too long to look up>")
def __len__(self):
return len(glob.glob('lmd_*'))
t = LessMemoryDict()
t['a'] = 'asdf'
print t['a']
print len(t)
print t
print t['b']
t['dog']['perro'] = .4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment