Skip to content

Instantly share code, notes, and snippets.

@stefco
Created July 10, 2017 15:06
Show Gist options
  • Save stefco/8e26740896ca106e8e30bd6674bf2964 to your computer and use it in GitHub Desktop.
Save stefco/8e26740896ca106e8e30bd6674bf2964 to your computer and use it in GitHub Desktop.
Some useful decorators and classes for Python
# (c) Stefan Countryman 2017
# useful classes and decorators for Python code, particularly python 2.7
def multiprocessing_traceback(func):
"""A decorator for formatting exception traceback into a string to aid in
debugging when using the ``multiprocessing`` module."""
import traceback, functools
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
msg = "{}\n\nOriginal {}".format(e, traceback.format_exc())
raise type(e)(msg)
return wrapper
class Cacheable(object):
"""An object that can store the output of property getter functions in a
"private" cache to avoid regeneration times. The cache can be flushed if
data needs to be regenerated from sources."""
@staticmethod
def _cacheable(property_func):
"""A decorator that makes an object property cacheable, i.e. the
function generating the data will not be called if the data has
already been generated. This can be cancelled by flushing cache."""
def wrapper(self, *args, **kwargs):
if not hasattr(self, '_cache'):
setattr(self, '_cache', dict())
prop_key = str(hash(property_func))
if not self._cache.has_key(prop_key):
self._cache[prop_key] = property_func(self, *args, **kwargs)
return self._cache[prop_key]
return wrapper
def _clear_cache(obj):
"""Delete the _cache property used by the @_cacheable decorator (if
present)."""
if hasattr(obj, '_cache'):
delattr('_cache')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment