Permalink
Browse files

some pyflakes + PEP8 cleanup

svn path=/plone.memoize/trunk/; revision=48572
  • Loading branch information...
1 parent 6ee14be commit 59b217e2073a114401ffd3e7069f77437e8484a6 WouterVH committed Apr 9, 2011
@@ -0,0 +1 @@
+#
View
@@ -11,11 +11,15 @@
_memos = {}
+
def memoize(fun):
+
def get_key(fun, *args, **kwargs):
- return (args, frozenset(kwargs.items()),)
+ return (args, frozenset(kwargs.items()), )
+
def get_cache(fun, *args, **kwargs):
return _memos
+
return volatile.cache(get_key, get_cache)(fun)
-__all__ = (memoize,)
+__all__ = (memoize, )
@@ -1,6 +1,6 @@
-=====================
+===================
forever decorators
-=====================
+===================
These remember a value "forever", i.e. until the process is restarted. They
work on both global functions and class functions.
@@ -45,4 +45,4 @@ This also works for methods in classes.
Calculating
3
>>> t.remember(1, 2)
- 3
+ 3
View
@@ -7,28 +7,34 @@
"""
_marker = object()
+
+
class Memojito(object):
propname = '_memojito_'
+
def clear(self, inst):
if hasattr(inst, self.propname):
delattr(inst, self.propname)
-
+
def clearbefore(self, func):
+
def clear(*args, **kwargs):
inst=args[0]
self.clear(inst)
return func(*args, **kwargs)
return clear
def clearafter(self, func):
+
def clear(*args, **kwargs):
inst=args[0]
val = func(*args, **kwargs)
self.clear(inst)
- return val
+ return val
return clear
def memoize(self, func):
+
def memogetter(*args, **kwargs):
inst = args[0]
cache = getattr(inst, self.propname, _marker)
@@ -54,6 +60,7 @@ def memogetter(*args, **kwargs):
clearbefore = _m.clearbefore
clearafter = _m.clearafter
+
def memoizedproperty(func):
return property(_m.memoize(func))
@@ -1,6 +1,6 @@
-=====================
+====================
instance decorators
-=====================
+====================
Originally from Whit Morriss' memojito package, they are used to
memoize return values for methods on an instance. The memoized values
@@ -1,5 +1,6 @@
from zope.interface import Interface
+
class ICacheChooser(Interface):
def __call__(fun_name):
@@ -9,12 +10,13 @@ def __call__(fun_name):
May return None to indicate that there is no cache available.
"""
+
class IXHTMLCompressor(Interface):
def compress(string):
"""Expects a valid XHTML Unicode string as input and returns a valid
XHTML Unicode string.
-
+
Examples of compression are removal of whitespace without a semantical
meaning, lowercasing of tags and attribute names (which gzip
compression can take advantage of) or removal of comments.
View
@@ -116,14 +116,18 @@
DontCache = volatile.DontCache
MARKER = object()
+
class AbstractDict:
+
def get(self, key, default=None):
try:
return self.__getitem__(key)
except KeyError:
return default
+
class MemcacheAdapter(AbstractDict):
+
def __init__(self, client, globalkey=''):
self.client = client
self.globalkey = globalkey and '%s:' % globalkey
@@ -144,7 +148,9 @@ def __setitem__(self, key, value):
cached_value = cPickle.dumps(value)
self.client.set(self.globalkey + self._make_key(key), cached_value)
+
class RAMCacheAdapter(AbstractDict):
+
def __init__(self, ramcache, globalkey=''):
self.ramcache = ramcache
self.globalkey = globalkey
@@ -168,11 +174,13 @@ def __setitem__(self, key, value):
self.globalkey,
dict(key=self._make_key(key)))
+
def choose_cache(fun_name):
return RAMCacheAdapter(component.queryUtility(IRAMCache),
globalkey=fun_name)
interface.directlyProvides(choose_cache, ICacheChooser)
+
def store_in_cache(fun, *args, **kwargs):
key = '%s.%s' % (fun.__module__, fun.__name__)
cache_chooser = component.queryUtility(ICacheChooser)
@@ -181,5 +189,6 @@ def store_in_cache(fun, *args, **kwargs):
else:
return RAMCacheAdapter(global_cache, globalkey=key)
+
def cache(get_key):
return volatile.cache(get_key, get_cache=store_in_cache)
View
@@ -11,14 +11,17 @@
from plone.memoize import volatile
_marker = object()
+
+
class RequestMemo(object):
-
+
key = 'plone.memoize_request'
def __init__(self, arg=0):
self.arg = arg
def __call__(self, func):
+
def memogetter(*args, **kwargs):
request = None
if isinstance(self.arg, int):
@@ -28,19 +31,21 @@ def memogetter(*args, **kwargs):
annotations = IAnnotations(request)
cache = annotations.get(self.key, _marker)
-
+
if cache is _marker:
cache = annotations[self.key] = dict()
-
- key = (func.__module__, func.__name__,
+
+ key = (func.__module__, func.__name__,
args, frozenset(kwargs.items()))
value = cache.get(key, _marker)
if value is _marker:
value = cache[key] = func(*args, **kwargs)
return value
return memogetter
+
def store_in_annotation_of(expr):
+
def _store_in_annotation(fun, *args, **kwargs):
# Use expr to find out the name of the request variable
vars = {}
@@ -49,8 +54,8 @@ def _store_in_annotation(fun, *args, **kwargs):
expected_num_args = num_args
# Explicitly check for the correct number of arguments and
- # raise the appropriate TypeError if needed. This is done
- # to avoid the real problem being masked by an IndexError
+ # raise the appropriate TypeError if needed. This is done
+ # to avoid the real problem being masked by an IndexError
# later in this method.
if spec[3] is not None:
expected_num_args = len(spec[0]) - len(spec[3])
@@ -67,12 +72,13 @@ def _store_in_annotation(fun, *args, **kwargs):
return IAnnotations(request)
return _store_in_annotation
+
def cache(get_key, get_request='request'):
r"""
This is a hypothetical function `increment` that'll store the
cache value on `a.request`, where a is the only argument to the
function:
-
+
>>> def increment(a):
... print 'Someone or something called me'
... return a + 1
@@ -100,7 +106,7 @@ def cache(get_key, get_request='request'):
generating the key. `get_request` will tell the decorator how to
actually find the `request` in the variable scope of the function
itself:
-
+
>>> cached_increment = \
... cache(get_key=get_key, get_request='a.request')(increment)
@@ -128,8 +134,8 @@ def cache(get_key, get_request='request'):
>>> IAnnotations(A.request)['plone.memoize.request.increment_plus:42']
43
- Create a function that can also take keyword arguments. For the sake of
- convenience pass the request explicitly. get_key must be modified to take
+ Create a function that can also take keyword arguments. For the sake of
+ convenience pass the request explicitly. get_key must be modified to take
kwargs into account:
>>> def get_key(fun, a, request, **kwargs):
View
@@ -21,17 +21,17 @@ def test_suite():
setUp=configurationSetUp,
tearDown=tearDown,
optionflags=optionflags),
- doctest.DocFileSuite('instance.txt',
+ doctest.DocFileSuite('instance.txt',
package="plone.memoize",
setUp=configurationSetUp,
tearDown=tearDown,
optionflags=optionflags),
- doctest.DocFileSuite('view.txt',
+ doctest.DocFileSuite('view.txt',
package="plone.memoize",
setUp=configurationSetUp,
tearDown=tearDown,
optionflags=optionflags),
- doctest.DocFileSuite('forever.txt',
+ doctest.DocFileSuite('forever.txt',
package="plone.memoize",
setUp=configurationSetUp,
tearDown=tearDown,
View
@@ -7,14 +7,17 @@
from zope.annotation.interfaces import IAnnotations
_marker = object()
+
+
class ViewMemo(object):
-
+
key = 'plone.memoize'
-
+
def memoize(self, func):
+
def memogetter(*args, **kwargs):
instance = args[0]
-
+
context = getattr(instance, 'context', None)
request = getattr(instance, 'request', None)
@@ -27,12 +30,12 @@ def memogetter(*args, **kwargs):
# XXX: Not the most elegant thing in the world; in a Zope 2
# context, the physical path is a better key, since the id could
# change if the object is invalidated from the ZODB cache
-
+
try:
context_id = context.getPhysicalPath()
except AttributeError:
context_id = id(context)
-
+
# Note: we don't use args[0] in the cache key, since args[0] ==
# instance and the whole point is that we can cache different
# requests
@@ -46,6 +49,7 @@ def memogetter(*args, **kwargs):
return memogetter
def memoize_contextless(self, func):
+
def memogetter(*args, **kwargs):
instance = args[0]
request = getattr(instance, 'request', None)
View
@@ -1,6 +1,6 @@
-======================
+=====================
view memo decorators
-======================
+=====================
Decorators for methods/properties in views. Values are cached by annotating
the view's request, and keyed based on the context and any arguments to the
@@ -198,6 +198,7 @@ class again, this time with a cached `pow` method:
import time
+
class CleanupDict(dict):
"""A dict that automatically cleans up items that haven't been
accessed in a given timespan on *set*.
@@ -253,17 +254,23 @@ def _cleanup(self):
CONTAINER_FACTORY = CleanupDict
_marker = object()
+
class DontCache(Exception):
pass
+
def store_on_self(method, obj, *args, **kwargs):
return obj.__dict__.setdefault(ATTR, CONTAINER_FACTORY())
+
def store_on_context(method, obj, *args, **kwargs):
return obj.context.__dict__.setdefault(ATTR, CONTAINER_FACTORY())
+
def cache(get_key, get_cache=store_on_self):
+
def decorator(fun):
+
def replacement(*args, **kwargs):
try:
key = get_key(fun, *args, **kwargs)

0 comments on commit 59b217e

Please sign in to comment.