Back to index

python3.2  3.2.2
Functions | Variables
functools Namespace Reference

Functions

def update_wrapper
def wraps
def total_ordering
def cmp_to_key
def lru_cache

Variables

list __all__
tuple WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__', '__annotations__')
tuple WRAPPER_UPDATES = ('__dict__',)
tuple _CacheInfo = namedtuple("CacheInfo", "hits misses maxsize currsize")
 obj

Detailed Description

functools.py - Tools for working with functions and callable objects

Function Documentation

def functools.cmp_to_key (   mycmp)
Convert a cmp= function into a key= function

Definition at line 96 of file functools.py.

00096 
00097 def cmp_to_key(mycmp):
00098     """Convert a cmp= function into a key= function"""
00099     class K(object):
00100         __slots__ = ['obj']
00101         def __init__(self, obj):
00102             self.obj = obj
00103         def __lt__(self, other):
00104             return mycmp(self.obj, other.obj) < 0
00105         def __gt__(self, other):
00106             return mycmp(self.obj, other.obj) > 0
00107         def __eq__(self, other):
00108             return mycmp(self.obj, other.obj) == 0
00109         def __le__(self, other):
00110             return mycmp(self.obj, other.obj) <= 0
00111         def __ge__(self, other):
00112             return mycmp(self.obj, other.obj) >= 0
00113         def __ne__(self, other):
00114             return mycmp(self.obj, other.obj) != 0
00115         __hash__ = None
00116     return K

Here is the call graph for this function:

Here is the caller graph for this function:

def functools.lru_cache (   maxsize = 100)
Least-recently-used cache decorator.

If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.

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__.

See:  http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used

Definition at line 119 of file functools.py.

00119 
00120 def lru_cache(maxsize=100):
00121     """Least-recently-used cache decorator.
00122 
00123     If *maxsize* is set to None, the LRU features are disabled and the cache
00124     can grow without bound.
00125 
00126     Arguments to the cached function must be hashable.
00127 
00128     View the cache statistics named tuple (hits, misses, maxsize, currsize) with
00129     f.cache_info().  Clear the cache and statistics with f.cache_clear().
00130     Access the underlying function with f.__wrapped__.
00131 
00132     See:  http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
00133 
00134     """
00135     # Users should only access the lru_cache through its public API:
00136     #       cache_info, cache_clear, and f.__wrapped__
00137     # The internals of the lru_cache are encapsulated for thread safety and
00138     # to allow the implementation to change (including a possible C version).
00139 
00140     def decorating_function(user_function,
00141                 tuple=tuple, sorted=sorted, len=len, KeyError=KeyError):
00142 
00143         hits = misses = 0
00144         kwd_mark = (object(),)          # separates positional and keyword args
00145         lock = Lock()                   # needed because ordereddicts aren't threadsafe
00146 
00147         if maxsize is None:
00148             cache = dict()              # simple cache without ordering or size limit
00149 
00150             @wraps(user_function)
00151             def wrapper(*args, **kwds):
00152                 nonlocal hits, misses
00153                 key = args
00154                 if kwds:
00155                     key += kwd_mark + tuple(sorted(kwds.items()))
00156                 try:
00157                     result = cache[key]
00158                     hits += 1
00159                 except KeyError:
00160                     result = user_function(*args, **kwds)
00161                     cache[key] = result
00162                     misses += 1
00163                 return result
00164         else:
00165             cache = OrderedDict()       # ordered least recent to most recent
00166             cache_popitem = cache.popitem
00167             cache_renew = cache.move_to_end
00168 
00169             @wraps(user_function)
00170             def wrapper(*args, **kwds):
00171                 nonlocal hits, misses
00172                 key = args
00173                 if kwds:
00174                     key += kwd_mark + tuple(sorted(kwds.items()))
00175                 try:
00176                     with lock:
00177                         result = cache[key]
00178                         cache_renew(key)        # record recent use of this key
00179                         hits += 1
00180                 except KeyError:
00181                     result = user_function(*args, **kwds)
00182                     with lock:
00183                         cache[key] = result     # record recent use of this key
00184                         misses += 1
00185                         if len(cache) > maxsize:
00186                             cache_popitem(0)    # purge least recently used cache entry
00187                 return result
00188 
00189         def cache_info():
00190             """Report cache statistics"""
00191             with lock:
00192                 return _CacheInfo(hits, misses, maxsize, len(cache))
00193 
00194         def cache_clear():
00195             """Clear the cache and cache statistics"""
00196             nonlocal hits, misses
00197             with lock:
00198                 cache.clear()
00199                 hits = misses = 0
00200 
00201         wrapper.cache_info = cache_info
00202         wrapper.cache_clear = cache_clear
00203         return wrapper
00204 
00205     return decorating_function

Here is the call graph for this function:

Here is the caller graph for this function:

def functools.total_ordering (   cls)
Class decorator that fills in missing ordering methods

Definition at line 68 of file functools.py.

00068 
00069 def total_ordering(cls):
00070     """Class decorator that fills in missing ordering methods"""
00071     convert = {
00072         '__lt__': [('__gt__', lambda self, other: not (self < other or self == other)),
00073                    ('__le__', lambda self, other: self < other or self == other),
00074                    ('__ge__', lambda self, other: not self < other)],
00075         '__le__': [('__ge__', lambda self, other: not self <= other or self == other),
00076                    ('__lt__', lambda self, other: self <= other and not self == other),
00077                    ('__gt__', lambda self, other: not self <= other)],
00078         '__gt__': [('__lt__', lambda self, other: not (self > other or self == other)),
00079                    ('__ge__', lambda self, other: self > other or self == other),
00080                    ('__le__', lambda self, other: not self > other)],
00081         '__ge__': [('__le__', lambda self, other: (not self >= other) or self == other),
00082                    ('__gt__', lambda self, other: self >= other and not self == other),
00083                    ('__lt__', lambda self, other: not self >= other)]
00084     }
00085     # Find user-defined comparisons (not those inherited from object).
00086     roots = [op for op in convert if getattr(cls, op, None) is not getattr(object, op, None)]
00087     if not roots:
00088         raise ValueError('must define at least one ordering operation: < > <= >=')
00089     root = max(roots)       # prefer __lt__ to __le__ to __gt__ to __ge__
00090     for opname, opfunc in convert[root]:
00091         if opname not in roots:
00092             opfunc.__name__ = opname
00093             opfunc.__doc__ = getattr(int, opname).__doc__
00094             setattr(cls, opname, opfunc)
00095     return cls

Here is the call graph for this function:

def functools.update_wrapper (   wrapper,
  wrapped,
  assigned = WRAPPER_ASSIGNMENTS,
  updated = WRAPPER_UPDATES 
)
Update a wrapper function to look like the wrapped function

   wrapper is the function to be updated
   wrapped is the original function
   assigned is a tuple naming the attributes assigned directly
   from the wrapped function to the wrapper function (defaults to
   functools.WRAPPER_ASSIGNMENTS)
   updated is a tuple naming the attributes of the wrapper that
   are updated with the corresponding attribute from the wrapped
   function (defaults to functools.WRAPPER_UPDATES)

Definition at line 29 of file functools.py.

00029 
00030                    updated = WRAPPER_UPDATES):
00031     """Update a wrapper function to look like the wrapped function
00032 
00033        wrapper is the function to be updated
00034        wrapped is the original function
00035        assigned is a tuple naming the attributes assigned directly
00036        from the wrapped function to the wrapper function (defaults to
00037        functools.WRAPPER_ASSIGNMENTS)
00038        updated is a tuple naming the attributes of the wrapper that
00039        are updated with the corresponding attribute from the wrapped
00040        function (defaults to functools.WRAPPER_UPDATES)
00041     """
00042     wrapper.__wrapped__ = wrapped
00043     for attr in assigned:
00044         try:
00045             value = getattr(wrapped, attr)
00046         except AttributeError:
00047             pass
00048         else:
00049             setattr(wrapper, attr, value)
00050     for attr in updated:
00051         getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
00052     # Return the wrapper so this can be used as a decorator via partial()
00053     return wrapper

Here is the call graph for this function:

Here is the caller graph for this function:

def functools.wraps (   wrapped,
  assigned = WRAPPER_ASSIGNMENTS,
  updated = WRAPPER_UPDATES 
)
Decorator factory to apply update_wrapper() to a wrapper function

   Returns a decorator that invokes update_wrapper() with the decorated
   function as the wrapper argument and the arguments to wraps() as the
   remaining arguments. Default arguments are as for update_wrapper().
   This is a convenience function to simplify applying partial() to
   update_wrapper().

Definition at line 56 of file functools.py.

00056 
00057           updated = WRAPPER_UPDATES):
00058     """Decorator factory to apply update_wrapper() to a wrapper function
00059 
00060        Returns a decorator that invokes update_wrapper() with the decorated
00061        function as the wrapper argument and the arguments to wraps() as the
00062        remaining arguments. Default arguments are as for update_wrapper().
00063        This is a convenience function to simplify applying partial() to
00064        update_wrapper().
00065     """
00066     return partial(update_wrapper, wrapped=wrapped,
00067                    assigned=assigned, updated=updated)

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

Initial value:
00001 ['update_wrapper', 'wraps', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES',
00002            'total_ordering', 'cmp_to_key', 'lru_cache', 'reduce', 'partial']

Definition at line 11 of file functools.py.

tuple functools._CacheInfo = namedtuple("CacheInfo", "hits misses maxsize currsize")

Definition at line 117 of file functools.py.

Definition at line 101 of file functools.py.

tuple functools.WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__', '__annotations__')

Definition at line 24 of file functools.py.

tuple functools.WRAPPER_UPDATES = ('__dict__',)

Definition at line 25 of file functools.py.