Index: Lib/functools.py =================================================================== --- Lib/functools.py (revision 87314) +++ Lib/functools.py (working copy) @@ -12,7 +12,8 @@ 'total_ordering', 'cmp_to_key', 'lru_cache', 'reduce', 'partial'] from _functools import partial, reduce -from collections import OrderedDict, namedtuple +from collections import OrderedDict, namedtuple, deque +import sys try: from _thread import allocate_lock as Lock except: @@ -114,8 +115,20 @@ raise TypeError('hash not implemented') return K -_CacheInfo = namedtuple("CacheInfo", "hits misses maxsize currsize") +_containers = (list, tuple, deque, dict, set, frozenset) +def _total_size(o): + 'Size of an object and all of its contents' + # XXX can getsizeof raise any exceptions for unknown types + s = sys.getsizeof(o) + if isinstance(o, _containers): + s += sum(map(total_size, o)) + if isinstance(o, dict): + s += sum(map(total_size, o.values())) + return s + +_CacheInfo = namedtuple("CacheInfo", "hits misses maxsize currsize kilobytes") + def lru_cache(maxsize=100): """Least-recently-used cache decorator. @@ -124,9 +137,9 @@ Arguments to the cached function must be hashable. - View the cache statistics named tuple (hits, misses, maxsize, currsize) with - f.cache_info(). Clear the cache and statistics with f.cache_clear(). - Access the underlying function with f.__wrapped__. + View the cache statistics named tuple (hits, misses, maxsize, currsize, + bytes) with f.cache_info(). Clear the cache and statistics with + f.cache_clear(). Access the underlying function with f.__wrapped__. See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used @@ -188,7 +201,8 @@ def cache_info(): """Report cache statistics""" with lock: - return _CacheInfo(hits, misses, maxsize, len(cache)) + return _CacheInfo(hits, misses, maxsize, len(cache), + _total_size(cache) // 1024) def cache_clear(): """Clear the cache and cache statistics"""