From 6c5d2c8b992732f5de300f160715653efb1cdfe2 Mon Sep 17 00:00:00 2001 From: Andreas Kloeckner <inform@tiker.net> Date: Sun, 7 Jul 2013 18:27:13 -0400 Subject: [PATCH] Use single implementation for memoize_method --- pytools/__init__.py | 55 ++++++++++++++++----------------------------- 1 file changed, 19 insertions(+), 36 deletions(-) diff --git a/pytools/__init__.py b/pytools/__init__.py index af84b1b..bb3412a 100644 --- a/pytools/__init__.py +++ b/pytools/__init__.py @@ -375,50 +375,33 @@ def memoize(func, *args): FunctionValueCache = memoize -if sys.version_info >= (2, 5): - # For Python 2.5 and newer, support cache deletion by a - # 'method_name.clear_cache(self)' call. +def memoize_method(method): + """Supports cache deletion via ``method_name.clear_cache(self)``.""" - def memoize_method(method): - cache_dict_name = intern("_memoize_dic_"+method.__name__) + cache_dict_name = intern("_memoize_dic_"+method.__name__) - def wrapper(self, *args): - try: - return getattr(self, cache_dict_name)[args] - except AttributeError: - result = method(self, *args) - setattr(self, cache_dict_name, {args: result}) - return result - except KeyError: - result = method(self, *args) - getattr(self, cache_dict_name)[args] = result - return result - - def clear_cache(self): - delattr(self, cache_dict_name) + def wrapper(self, *args): + try: + return getattr(self, cache_dict_name)[args] + except AttributeError: + result = method(self, *args) + setattr(self, cache_dict_name, {args: result}) + return result + except KeyError: + result = method(self, *args) + getattr(self, cache_dict_name)[args] = result + return result + + def clear_cache(self): + delattr(self, cache_dict_name) + if sys.version_info >= (2, 5): from functools import update_wrapper new_wrapper = update_wrapper(wrapper, method) new_wrapper.clear_cache = clear_cache - return new_wrapper + return new_wrapper -else: - # For sad old Python 2.4, cache deletion is not supported. - - @my_decorator - def memoize_method(method, instance, *args): - cache_dict_name = intern("_memoize_dic_"+method.__name__) - try: - return getattr(instance, cache_dict_name)[args] - except AttributeError: - result = method(instance, *args) - setattr(instance, cache_dict_name, {args: result}) - return result - except KeyError: - result = method(instance, *args) - getattr(instance, cache_dict_name)[args] = result - return result def memoize_method_nested(inner): -- GitLab