Skip to content

Instantly share code, notes, and snippets.

@jaredlockhart
Created December 15, 2015 20:02
Show Gist options
  • Save jaredlockhart/c70695f8bc5a00791eed to your computer and use it in GitHub Desktop.
Save jaredlockhart/c70695f8bc5a00791eed to your computer and use it in GitHub Desktop.
from uuid import uuid4
_cache = {}
def cache_set(key, value):
print 'Setting ', key, ' with value ', value
_cache[key] = value
def cache_get(key):
print 'Returning ', key, ' from cache'
if key in _cache:
print 'Cache hit!'
return _cache[key]
else:
print 'Cache miss!'
def cache_property(instance_key):
def decorated(method):
def wrapped(instance):
instance_cache_key = '{instance_prefix}:{instance_key}'.format(
instance_prefix=instance._instance_cache_prefix(),
instance_key=instance_key,
)
cached_value = cache_get(instance_cache_key)
if cached_value is not None:
return cached_value
else:
value = method(instance)
cache_set(instance_cache_key, value)
return value
return property(wrapped)
return decorated
class Book(object):
def __init__(self, author, title):
self.uid = uuid4().hex
self.author = author
self.title = title
def _instance_cache_prefix(self):
return self.uid
@cache_property('title')
def full_title(self):
print 'Computing full title'
return '{author} - {title}'.format(
author=self.author,
title=self.title,
)
book1 = Book('JK Rowling', 'The Nerds Stone')
print book1.full_title
print book1.full_title
book2 = Book('Tolkien', 'The Nerds Tower')
print book2.full_title
print book2.full_title
output:
Returning fd24815d90cf4c2692694e3a1bb91c93:title from cache
Cache miss!
Computing full title
Setting fd24815d90cf4c2692694e3a1bb91c93:title with value JK Rowling - The Nerds Stone
JK Rowling - The Nerds Stone
Returning fd24815d90cf4c2692694e3a1bb91c93:title from cache
Cache hit!
JK Rowling - The Nerds Stone
Returning fd319e3f1f0c4c4e9882bbb497e19876:title from cache
Cache miss!
Computing full title
Setting fd319e3f1f0c4c4e9882bbb497e19876:title with value Tolkien - The Nerds Tower
Tolkien - The Nerds Tower
Returning fd319e3f1f0c4c4e9882bbb497e19876:title from cache
Cache hit!
Tolkien - The Nerds Tower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment