blob: 103dd426e3fa2691cc03bd3bee66f24e8c9ca7ed [file] [log] [blame]
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001"""functools.py - Tools for working with functions and callable objects
Thomas Wouters4d70c3d2006-06-08 14:42:34 +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>
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007# Copyright (C) 2006 Python Software Foundation.
8# See C source code for _functools credits/copyright
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00009
Guido van Rossum0919a1a2006-08-26 20:49:04 +000010from _functools import partial, reduce
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000011
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000012# update_wrapper() and wraps() are tools to help write
13# wrapper functions that can handle naive introspection
14
Raymond Hettingerc6d80c12010-08-08 00:56:52 +000015WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__', '__annotations__')
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000016WRAPPER_UPDATES = ('__dict__',)
17def update_wrapper(wrapper,
18 wrapped,
19 assigned = WRAPPER_ASSIGNMENTS,
20 updated = WRAPPER_UPDATES):
21 """Update a wrapper function to look like the wrapped function
22
23 wrapper is the function to be updated
24 wrapped is the original function
25 assigned is a tuple naming the attributes assigned directly
26 from the wrapped function to the wrapper function (defaults to
27 functools.WRAPPER_ASSIGNMENTS)
Thomas Wouters89f507f2006-12-13 04:49:30 +000028 updated is a tuple naming the attributes of the wrapper that
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000029 are updated with the corresponding attribute from the wrapped
30 function (defaults to functools.WRAPPER_UPDATES)
31 """
32 for attr in assigned:
Raymond Hettingerc6d80c12010-08-08 00:56:52 +000033 if hasattr(wrapped, attr):
34 setattr(wrapper, attr, getattr(wrapped, attr))
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000035 for attr in updated:
Thomas Wouters89f507f2006-12-13 04:49:30 +000036 getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
Thomas Wouters73e5a5b2006-06-08 15:35:45 +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)