blob: 30e1d24fd2849269789cf76c6c9855949c4a99ad [file] [log] [blame]
Nick Coghlan676725d2006-06-08 13:54:49 +00001"""functools.py - Tools for working with functions and callable objects
Nick Coghlan08490142006-05-29 20:27:44 +00002"""
3# Python module wrapper for _functools C module
4# to allow utilities written in Python to be added
5# to the functools module.
6# Written by Nick Coghlan <ncoghlan at gmail.com>
Nick Coghlan676725d2006-06-08 13:54:49 +00007# Copyright (C) 2006 Python Software Foundation.
8# See C source code for _functools credits/copyright
Nick Coghlan08490142006-05-29 20:27:44 +00009
10from _functools import partial
Guido van Rossumd51b5792007-08-27 20:51:00 +000011from __builtin__ import reduce
Nick Coghlan08490142006-05-29 20:27:44 +000012
Nick Coghlan676725d2006-06-08 13:54:49 +000013# update_wrapper() and wraps() are tools to help write
14# wrapper functions that can handle naive introspection
15
16WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
17WRAPPER_UPDATES = ('__dict__',)
18def update_wrapper(wrapper,
19 wrapped,
20 assigned = WRAPPER_ASSIGNMENTS,
21 updated = WRAPPER_UPDATES):
22 """Update a wrapper function to look like the wrapped function
23
24 wrapper is the function to be updated
25 wrapped is the original function
26 assigned is a tuple naming the attributes assigned directly
27 from the wrapped function to the wrapper function (defaults to
28 functools.WRAPPER_ASSIGNMENTS)
Andrew M. Kuchlingefb57072006-10-26 19:16:46 +000029 updated is a tuple naming the attributes of the wrapper that
Nick Coghlan676725d2006-06-08 13:54:49 +000030 are updated with the corresponding attribute from the wrapped
31 function (defaults to functools.WRAPPER_UPDATES)
32 """
33 for attr in assigned:
34 setattr(wrapper, attr, getattr(wrapped, attr))
35 for attr in updated:
Andrew M. Kuchling41eb7162006-10-27 16:39:10 +000036 getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
Nick Coghlan676725d2006-06-08 13:54:49 +000037 # Return the wrapper so this can be used as a decorator via partial()
38 return wrapper
39
40def wraps(wrapped,
41 assigned = WRAPPER_ASSIGNMENTS,
42 updated = WRAPPER_UPDATES):
43 """Decorator factory to apply update_wrapper() to a wrapper function
44
45 Returns a decorator that invokes update_wrapper() with the decorated
46 function as the wrapper argument and the arguments to wraps() as the
47 remaining arguments. Default arguments are as for update_wrapper().
48 This is a convenience function to simplify applying partial() to
49 update_wrapper().
50 """
51 return partial(update_wrapper, wrapped=wrapped,
52 assigned=assigned, updated=updated)