Skip to content

Instantly share code, notes, and snippets.

@mloberg
Created March 2, 2018 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mloberg/fb7fb137e743901822f0ba8ccb2b580e to your computer and use it in GitHub Desktop.
Save mloberg/fb7fb137e743901822f0ba8ccb2b580e to your computer and use it in GitHub Desktop.
Python Tools
from itertools import islice, chain
def batch(iterable, size):
iterator = iter(iterable)
for first in iterator:
yield chain([first], islice(iterator, size - 1))
import os
import pickle
def cache(function):
def wrapper(*args, **kwargs):
key = '.cache/%s-%s' % (function.__name__, ','.join(args))
if os.path.exists(key):
with open(key, 'rb') as f:
return pickle.load(f)
result = function(*args, **kwargs)
path, filename = os.path.split(key)
os.makedirs(path, exist_ok=True)
with open(key, 'wb') as f:
pickle.dump(result, f)
return result
return wrapper
@cache
def expensive_call():
"""Some expensive function call"""
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment