blob: 1b94f3396005323d71847c194f050bea36862ff9 [file] [log] [blame]
Georg Brandl6c89a792012-01-25 22:36:25 +01001:mod:`functools` --- Higher-order functions and operations on callable objects
Georg Brandl116aa622007-08-15 14:28:22 +00002==============================================================================
3
4.. module:: functools
Georg Brandl6c89a792012-01-25 22:36:25 +01005 :synopsis: Higher-order functions and operations on callable objects.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Peter Harris <scav@blueyonder.co.uk>
8.. moduleauthor:: Raymond Hettinger <python@rcn.com>
9.. moduleauthor:: Nick Coghlan <ncoghlan@gmail.com>
Łukasz Langa6f692512013-06-05 12:20:24 +020010.. moduleauthor:: Łukasz Langa <lukasz@langa.pl>
Georg Brandl116aa622007-08-15 14:28:22 +000011.. sectionauthor:: Peter Harris <scav@blueyonder.co.uk>
12
Raymond Hettinger05ce0792011-01-10 21:16:07 +000013**Source code:** :source:`Lib/functools.py`
14
15--------------
Georg Brandl116aa622007-08-15 14:28:22 +000016
Georg Brandl116aa622007-08-15 14:28:22 +000017The :mod:`functools` module is for higher-order functions: functions that act on
18or return other functions. In general, any callable object can be treated as a
19function for the purposes of this module.
20
Thomas Woutersed03b412007-08-28 21:37:11 +000021The :mod:`functools` module defines the following functions:
22
Carl Meyerd658dea2018-08-28 01:11:56 -060023.. decorator:: cached_property(func)
24
25 Transform a method of a class into a property whose value is computed once
26 and then cached as a normal attribute for the life of the instance. Similar
27 to :func:`property`, with the addition of caching. Useful for expensive
28 computed properties of instances that are otherwise effectively immutable.
29
30 Example::
31
32 class DataSet:
33 def __init__(self, sequence_of_numbers):
34 self._data = sequence_of_numbers
35
36 @cached_property
37 def stdev(self):
38 return statistics.stdev(self._data)
39
40 @cached_property
41 def variance(self):
42 return statistics.variance(self._data)
43
44 .. versionadded:: 3.8
45
46 .. note::
47
48 This decorator requires that the ``__dict__`` attribute on each instance
49 be a mutable mapping. This means it will not work with some types, such as
50 metaclasses (since the ``__dict__`` attributes on type instances are
51 read-only proxies for the class namespace), and those that specify
52 ``__slots__`` without including ``__dict__`` as one of the defined slots
53 (as such classes don't provide a ``__dict__`` attribute at all).
54
55
Éric Araujob10089e2010-11-18 14:22:08 +000056.. function:: cmp_to_key(func)
Raymond Hettingerc50846a2010-04-05 18:56:31 +000057
Raymond Hettinger86e9b6b2014-11-09 17:20:56 -080058 Transform an old-style comparison function to a :term:`key function`. Used
59 with tools that accept key functions (such as :func:`sorted`, :func:`min`,
Benjamin Petersoncca65312010-08-09 02:13:10 +000060 :func:`max`, :func:`heapq.nlargest`, :func:`heapq.nsmallest`,
61 :func:`itertools.groupby`). This function is primarily used as a transition
Ezio Melotti9ecb6be2012-01-16 08:28:54 +020062 tool for programs being converted from Python 2 which supported the use of
Benjamin Petersoncca65312010-08-09 02:13:10 +000063 comparison functions.
Raymond Hettingerc50846a2010-04-05 18:56:31 +000064
Georg Brandl6c89a792012-01-25 22:36:25 +010065 A comparison function is any callable that accept two arguments, compares them,
Benjamin Petersoncca65312010-08-09 02:13:10 +000066 and returns a negative number for less-than, zero for equality, or a positive
67 number for greater-than. A key function is a callable that accepts one
Raymond Hettinger86e9b6b2014-11-09 17:20:56 -080068 argument and returns another value to be used as the sort key.
Raymond Hettingerc50846a2010-04-05 18:56:31 +000069
Benjamin Petersoncca65312010-08-09 02:13:10 +000070 Example::
Raymond Hettingerc50846a2010-04-05 18:56:31 +000071
Benjamin Petersoncca65312010-08-09 02:13:10 +000072 sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order
Raymond Hettingerc50846a2010-04-05 18:56:31 +000073
Raymond Hettinger86e9b6b2014-11-09 17:20:56 -080074 For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`.
75
Raymond Hettingerc50846a2010-04-05 18:56:31 +000076 .. versionadded:: 3.2
77
Georg Brandl67b21b72010-08-17 15:07:14 +000078
Raymond Hettinger010ce322012-05-19 21:20:48 -070079.. decorator:: lru_cache(maxsize=128, typed=False)
Georg Brandl2e7346a2010-07-31 18:09:23 +000080
81 Decorator to wrap a function with a memoizing callable that saves up to the
82 *maxsize* most recent calls. It can save time when an expensive or I/O bound
83 function is periodically called with the same arguments.
84
Raymond Hettinger7496b412010-11-30 19:15:45 +000085 Since a dictionary is used to cache results, the positional and keyword
86 arguments to the function must be hashable.
Georg Brandl2e7346a2010-07-31 18:09:23 +000087
Serhiy Storchakaecf41da2016-10-19 16:29:26 +030088 If *maxsize* is set to ``None``, the LRU feature is disabled and the cache can
Raymond Hettinger7d74eff2012-06-04 00:32:15 -070089 grow without bound. The LRU feature performs best when *maxsize* is a
90 power-of-two.
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +000091
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +030092 If *typed* is set to true, function arguments of different types will be
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -070093 cached separately. For example, ``f(3)`` and ``f(3.0)`` will be treated
94 as distinct calls with distinct results.
95
Raymond Hettinger7496b412010-11-30 19:15:45 +000096 To help measure the effectiveness of the cache and tune the *maxsize*
97 parameter, the wrapped function is instrumented with a :func:`cache_info`
98 function that returns a :term:`named tuple` showing *hits*, *misses*,
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +000099 *maxsize* and *currsize*. In a multi-threaded environment, the hits
100 and misses are approximate.
Nick Coghlan234515a2010-11-30 06:19:46 +0000101
Raymond Hettinger7496b412010-11-30 19:15:45 +0000102 The decorator also provides a :func:`cache_clear` function for clearing or
103 invalidating the cache.
Georg Brandl2e7346a2010-07-31 18:09:23 +0000104
Raymond Hettinger3fccfcb2010-08-17 19:19:29 +0000105 The original underlying function is accessible through the
Raymond Hettinger7496b412010-11-30 19:15:45 +0000106 :attr:`__wrapped__` attribute. This is useful for introspection, for
107 bypassing the cache, or for rewrapping the function with a different cache.
Nick Coghlan98876832010-08-17 06:17:18 +0000108
Raymond Hettingercc038582010-11-30 20:02:57 +0000109 An `LRU (least recently used) cache
Georg Brandl5d941342016-02-26 19:37:12 +0100110 <https://en.wikipedia.org/wiki/Cache_algorithms#Examples>`_ works
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -0700111 best when the most recent calls are the best predictors of upcoming calls (for
112 example, the most popular articles on a news server tend to change each day).
Raymond Hettinger7496b412010-11-30 19:15:45 +0000113 The cache's size limit assures that the cache does not grow without bound on
114 long-running processes such as web servers.
115
Raymond Hettingercc038582010-11-30 20:02:57 +0000116 Example of an LRU cache for static web content::
Raymond Hettinger7496b412010-11-30 19:15:45 +0000117
Raymond Hettinger17328e42013-04-06 20:27:33 -0700118 @lru_cache(maxsize=32)
Raymond Hettinger7496b412010-11-30 19:15:45 +0000119 def get_pep(num):
120 'Retrieve text of a Python Enhancement Proposal'
121 resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
122 try:
123 with urllib.request.urlopen(resource) as s:
124 return s.read()
125 except urllib.error.HTTPError:
126 return 'Not Found'
127
128 >>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
129 ... pep = get_pep(n)
130 ... print(n, len(pep))
131
Raymond Hettinger17328e42013-04-06 20:27:33 -0700132 >>> get_pep.cache_info()
133 CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
Georg Brandl2e7346a2010-07-31 18:09:23 +0000134
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000135 Example of efficiently computing
Georg Brandl5d941342016-02-26 19:37:12 +0100136 `Fibonacci numbers <https://en.wikipedia.org/wiki/Fibonacci_number>`_
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000137 using a cache to implement a
Georg Brandl5d941342016-02-26 19:37:12 +0100138 `dynamic programming <https://en.wikipedia.org/wiki/Dynamic_programming>`_
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000139 technique::
140
141 @lru_cache(maxsize=None)
142 def fib(n):
143 if n < 2:
144 return n
145 return fib(n-1) + fib(n-2)
146
Raymond Hettinger17328e42013-04-06 20:27:33 -0700147 >>> [fib(n) for n in range(16)]
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000148 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
149
Raymond Hettinger17328e42013-04-06 20:27:33 -0700150 >>> fib.cache_info()
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000151 CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
152
Georg Brandl2e7346a2010-07-31 18:09:23 +0000153 .. versionadded:: 3.2
154
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -0700155 .. versionchanged:: 3.3
156 Added the *typed* option.
157
Georg Brandl8a1caa22010-07-29 16:01:11 +0000158.. decorator:: total_ordering
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000159
160 Given a class defining one or more rich comparison ordering methods, this
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000161 class decorator supplies the rest. This simplifies the effort involved
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000162 in specifying all of the possible rich comparison operations:
163
164 The class must define one of :meth:`__lt__`, :meth:`__le__`,
165 :meth:`__gt__`, or :meth:`__ge__`.
166 In addition, the class should supply an :meth:`__eq__` method.
167
168 For example::
169
170 @total_ordering
171 class Student:
Nick Coghlanf05d9812013-10-02 00:02:03 +1000172 def _is_valid_operand(self, other):
173 return (hasattr(other, "lastname") and
174 hasattr(other, "firstname"))
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000175 def __eq__(self, other):
Nick Coghlanf05d9812013-10-02 00:02:03 +1000176 if not self._is_valid_operand(other):
177 return NotImplemented
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000178 return ((self.lastname.lower(), self.firstname.lower()) ==
179 (other.lastname.lower(), other.firstname.lower()))
180 def __lt__(self, other):
Nick Coghlanf05d9812013-10-02 00:02:03 +1000181 if not self._is_valid_operand(other):
182 return NotImplemented
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000183 return ((self.lastname.lower(), self.firstname.lower()) <
184 (other.lastname.lower(), other.firstname.lower()))
185
Nick Coghlanf05d9812013-10-02 00:02:03 +1000186 .. note::
187
188 While this decorator makes it easy to create well behaved totally
189 ordered types, it *does* come at the cost of slower execution and
190 more complex stack traces for the derived comparison methods. If
191 performance benchmarking indicates this is a bottleneck for a given
192 application, implementing all six rich comparison methods instead is
193 likely to provide an easy speed boost.
194
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000195 .. versionadded:: 3.2
196
Nick Coghlanf05d9812013-10-02 00:02:03 +1000197 .. versionchanged:: 3.4
198 Returning NotImplemented from the underlying comparison function for
199 unrecognised types is now supported.
Georg Brandl67b21b72010-08-17 15:07:14 +0000200
Georg Brandl036490d2009-05-17 13:00:36 +0000201.. function:: partial(func, *args, **keywords)
Georg Brandl116aa622007-08-15 14:28:22 +0000202
203 Return a new :class:`partial` object which when called will behave like *func*
204 called with the positional arguments *args* and keyword arguments *keywords*. If
205 more arguments are supplied to the call, they are appended to *args*. If
206 additional keyword arguments are supplied, they extend and override *keywords*.
207 Roughly equivalent to::
208
209 def partial(func, *args, **keywords):
210 def newfunc(*fargs, **fkeywords):
211 newkeywords = keywords.copy()
212 newkeywords.update(fkeywords)
Martin Panter0c0da482016-06-12 01:46:50 +0000213 return func(*args, *fargs, **newkeywords)
Georg Brandl116aa622007-08-15 14:28:22 +0000214 newfunc.func = func
215 newfunc.args = args
216 newfunc.keywords = keywords
217 return newfunc
218
219 The :func:`partial` is used for partial function application which "freezes"
220 some portion of a function's arguments and/or keywords resulting in a new object
221 with a simplified signature. For example, :func:`partial` can be used to create
222 a callable that behaves like the :func:`int` function where the *base* argument
Christian Heimesfe337bf2008-03-23 21:54:12 +0000223 defaults to two:
Georg Brandl116aa622007-08-15 14:28:22 +0000224
Christian Heimesfe337bf2008-03-23 21:54:12 +0000225 >>> from functools import partial
Georg Brandl116aa622007-08-15 14:28:22 +0000226 >>> basetwo = partial(int, base=2)
227 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
228 >>> basetwo('10010')
229 18
230
231
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000232.. class:: partialmethod(func, *args, **keywords)
233
234 Return a new :class:`partialmethod` descriptor which behaves
235 like :class:`partial` except that it is designed to be used as a method
236 definition rather than being directly callable.
237
238 *func* must be a :term:`descriptor` or a callable (objects which are both,
239 like normal functions, are handled as descriptors).
240
241 When *func* is a descriptor (such as a normal Python function,
242 :func:`classmethod`, :func:`staticmethod`, :func:`abstractmethod` or
243 another instance of :class:`partialmethod`), calls to ``__get__`` are
244 delegated to the underlying descriptor, and an appropriate
245 :class:`partial` object returned as the result.
246
247 When *func* is a non-descriptor callable, an appropriate bound method is
248 created dynamically. This behaves like a normal Python function when
249 used as a method: the *self* argument will be inserted as the first
250 positional argument, even before the *args* and *keywords* supplied to
251 the :class:`partialmethod` constructor.
252
253 Example::
254
255 >>> class Cell(object):
Benjamin Peterson3a434032014-03-30 15:07:09 -0400256 ... def __init__(self):
257 ... self._alive = False
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000258 ... @property
259 ... def alive(self):
260 ... return self._alive
261 ... def set_state(self, state):
262 ... self._alive = bool(state)
Nick Coghlan3daaf5f2013-11-04 23:32:16 +1000263 ... set_alive = partialmethod(set_state, True)
264 ... set_dead = partialmethod(set_state, False)
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000265 ...
266 >>> c = Cell()
267 >>> c.alive
268 False
269 >>> c.set_alive()
270 >>> c.alive
271 True
272
273 .. versionadded:: 3.4
274
275
Georg Brandl58f9e4f2008-04-19 22:18:33 +0000276.. function:: reduce(function, iterable[, initializer])
Georg Brandl116aa622007-08-15 14:28:22 +0000277
278 Apply *function* of two arguments cumulatively to the items of *sequence*, from
279 left to right, so as to reduce the sequence to a single value. For example,
280 ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``.
281 The left argument, *x*, is the accumulated value and the right argument, *y*, is
282 the update value from the *sequence*. If the optional *initializer* is present,
283 it is placed before the items of the sequence in the calculation, and serves as
284 a default when the sequence is empty. If *initializer* is not given and
285 *sequence* contains only one item, the first item is returned.
286
Raymond Hettinger558dcf32014-12-16 18:16:57 -0800287 Roughly equivalent to::
Raymond Hettinger64801682013-10-12 16:04:17 -0700288
289 def reduce(function, iterable, initializer=None):
290 it = iter(iterable)
291 if initializer is None:
292 value = next(it)
293 else:
294 value = initializer
295 for element in it:
296 value = function(value, element)
297 return value
298
Gerrit Hollbd81cbd2018-07-04 23:26:32 +0100299 See :func:`itertools.accumulate` for an iterator that yields all intermediate
300 values.
Georg Brandl116aa622007-08-15 14:28:22 +0000301
Daisuke Miyakawa0e61e672017-10-12 23:39:43 +0900302.. decorator:: singledispatch
Łukasz Langa6f692512013-06-05 12:20:24 +0200303
Daisuke Miyakawa0e61e672017-10-12 23:39:43 +0900304 Transform a function into a :term:`single-dispatch <single
Łukasz Langafdcf2b72013-06-07 22:54:03 +0200305 dispatch>` :term:`generic function`.
Łukasz Langa6f692512013-06-05 12:20:24 +0200306
307 To define a generic function, decorate it with the ``@singledispatch``
308 decorator. Note that the dispatch happens on the type of the first argument,
309 create your function accordingly::
310
311 >>> from functools import singledispatch
312 >>> @singledispatch
313 ... def fun(arg, verbose=False):
314 ... if verbose:
315 ... print("Let me just say,", end=" ")
316 ... print(arg)
317
318 To add overloaded implementations to the function, use the :func:`register`
Łukasz Langae5697532017-12-11 13:56:31 -0800319 attribute of the generic function. It is a decorator. For functions
320 annotated with types, the decorator will infer the type of the first
321 argument automatically::
Łukasz Langa6f692512013-06-05 12:20:24 +0200322
Łukasz Langae5697532017-12-11 13:56:31 -0800323 >>> @fun.register
324 ... def _(arg: int, verbose=False):
Łukasz Langa6f692512013-06-05 12:20:24 +0200325 ... if verbose:
326 ... print("Strength in numbers, eh?", end=" ")
327 ... print(arg)
328 ...
Łukasz Langae5697532017-12-11 13:56:31 -0800329 >>> @fun.register
330 ... def _(arg: list, verbose=False):
Łukasz Langa6f692512013-06-05 12:20:24 +0200331 ... if verbose:
332 ... print("Enumerate this:")
333 ... for i, elem in enumerate(arg):
334 ... print(i, elem)
335
Łukasz Langae5697532017-12-11 13:56:31 -0800336 For code which doesn't use type annotations, the appropriate type
337 argument can be passed explicitly to the decorator itself::
338
339 >>> @fun.register(complex)
340 ... def _(arg, verbose=False):
341 ... if verbose:
342 ... print("Better than complicated.", end=" ")
343 ... print(arg.real, arg.imag)
344 ...
345
346
Łukasz Langa6f692512013-06-05 12:20:24 +0200347 To enable registering lambdas and pre-existing functions, the
348 :func:`register` attribute can be used in a functional form::
349
350 >>> def nothing(arg, verbose=False):
351 ... print("Nothing.")
352 ...
353 >>> fun.register(type(None), nothing)
354
355 The :func:`register` attribute returns the undecorated function which
356 enables decorator stacking, pickling, as well as creating unit tests for
357 each variant independently::
358
359 >>> @fun.register(float)
360 ... @fun.register(Decimal)
361 ... def fun_num(arg, verbose=False):
362 ... if verbose:
363 ... print("Half of your number:", end=" ")
364 ... print(arg / 2)
365 ...
366 >>> fun_num is fun
367 False
368
369 When called, the generic function dispatches on the type of the first
370 argument::
371
372 >>> fun("Hello, world.")
373 Hello, world.
374 >>> fun("test.", verbose=True)
375 Let me just say, test.
376 >>> fun(42, verbose=True)
377 Strength in numbers, eh? 42
378 >>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)
379 Enumerate this:
380 0 spam
381 1 spam
382 2 eggs
383 3 spam
384 >>> fun(None)
385 Nothing.
386 >>> fun(1.23)
387 0.615
388
389 Where there is no registered implementation for a specific type, its
390 method resolution order is used to find a more generic implementation.
391 The original function decorated with ``@singledispatch`` is registered
392 for the base ``object`` type, which means it is used if no better
393 implementation is found.
394
395 To check which implementation will the generic function choose for
396 a given type, use the ``dispatch()`` attribute::
397
398 >>> fun.dispatch(float)
399 <function fun_num at 0x1035a2840>
400 >>> fun.dispatch(dict) # note: default implementation
401 <function fun at 0x103fe0000>
402
403 To access all registered implementations, use the read-only ``registry``
404 attribute::
405
406 >>> fun.registry.keys()
407 dict_keys([<class 'NoneType'>, <class 'int'>, <class 'object'>,
408 <class 'decimal.Decimal'>, <class 'list'>,
409 <class 'float'>])
410 >>> fun.registry[float]
411 <function fun_num at 0x1035a2840>
412 >>> fun.registry[object]
413 <function fun at 0x103fe0000>
414
415 .. versionadded:: 3.4
416
Łukasz Langae5697532017-12-11 13:56:31 -0800417 .. versionchanged:: 3.7
418 The :func:`register` attribute supports using type annotations.
419
Łukasz Langa6f692512013-06-05 12:20:24 +0200420
Ethan Smithc6512752018-05-26 16:38:33 -0400421.. class:: singledispatchmethod(func)
422
423 Transform a method into a :term:`single-dispatch <single
424 dispatch>` :term:`generic function`.
425
426 To define a generic method, decorate it with the ``@singledispatchmethod``
427 decorator. Note that the dispatch happens on the type of the first non-self
428 or non-cls argument, create your function accordingly::
429
430 class Negator:
431 @singledispatchmethod
432 def neg(self, arg):
433 raise NotImplementedError("Cannot negate a")
434
435 @neg.register
436 def _(self, arg: int):
437 return -arg
438
439 @neg.register
440 def _(self, arg: bool):
441 return not arg
442
443 ``@singledispatchmethod`` supports nesting with other decorators such as
444 ``@classmethod``. Note that to allow for ``dispatcher.register``,
445 ``singledispatchmethod`` must be the *outer most* decorator. Here is the
446 ``Negator`` class with the ``neg`` methods being class bound::
447
448 class Negator:
449 @singledispatchmethod
450 @classmethod
451 def neg(cls, arg):
452 raise NotImplementedError("Cannot negate a")
453
454 @neg.register
455 @classmethod
456 def _(cls, arg: int):
457 return -arg
458
459 @neg.register
460 @classmethod
461 def _(cls, arg: bool):
462 return not arg
463
464 The same pattern can be used for other similar decorators: ``staticmethod``,
465 ``abstractmethod``, and others.
466
Georg Brandl036490d2009-05-17 13:00:36 +0000467.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000468
469 Update a *wrapper* function to look like the *wrapped* function. The optional
470 arguments are tuples to specify which attributes of the original function are
471 assigned directly to the matching attributes on the wrapper function and which
472 attributes of the wrapper function are updated with the corresponding attributes
473 from the original function. The default values for these arguments are the
Berker Peksag472233e2016-04-18 21:20:50 +0300474 module level constants ``WRAPPER_ASSIGNMENTS`` (which assigns to the wrapper
475 function's ``__module__``, ``__name__``, ``__qualname__``, ``__annotations__``
476 and ``__doc__``, the documentation string) and ``WRAPPER_UPDATES`` (which
477 updates the wrapper function's ``__dict__``, i.e. the instance dictionary).
Georg Brandl116aa622007-08-15 14:28:22 +0000478
Nick Coghlan98876832010-08-17 06:17:18 +0000479 To allow access to the original function for introspection and other purposes
480 (e.g. bypassing a caching decorator such as :func:`lru_cache`), this function
Nick Coghlan24c05bc2013-07-15 21:13:08 +1000481 automatically adds a ``__wrapped__`` attribute to the wrapper that refers to
482 the function being wrapped.
Nick Coghlan98876832010-08-17 06:17:18 +0000483
Christian Heimesd8654cf2007-12-02 15:22:16 +0000484 The main intended use for this function is in :term:`decorator` functions which
485 wrap the decorated function and return the wrapper. If the wrapper function is
486 not updated, the metadata of the returned function will reflect the wrapper
Georg Brandl116aa622007-08-15 14:28:22 +0000487 definition rather than the original function definition, which is typically less
488 than helpful.
489
Nick Coghlan98876832010-08-17 06:17:18 +0000490 :func:`update_wrapper` may be used with callables other than functions. Any
491 attributes named in *assigned* or *updated* that are missing from the object
492 being wrapped are ignored (i.e. this function will not attempt to set them
493 on the wrapper function). :exc:`AttributeError` is still raised if the
494 wrapper function itself is missing any attributes named in *updated*.
495
496 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000497 Automatic addition of the ``__wrapped__`` attribute.
Nick Coghlan98876832010-08-17 06:17:18 +0000498
499 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000500 Copying of the ``__annotations__`` attribute by default.
Nick Coghlan98876832010-08-17 06:17:18 +0000501
502 .. versionchanged:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000503 Missing attributes no longer trigger an :exc:`AttributeError`.
504
Nick Coghlan24c05bc2013-07-15 21:13:08 +1000505 .. versionchanged:: 3.4
506 The ``__wrapped__`` attribute now always refers to the wrapped
507 function, even if that function defined a ``__wrapped__`` attribute.
508 (see :issue:`17482`)
509
Georg Brandl116aa622007-08-15 14:28:22 +0000510
Georg Brandl8a1caa22010-07-29 16:01:11 +0000511.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000512
Ezio Melotti67f6d5f2014-08-05 08:14:28 +0300513 This is a convenience function for invoking :func:`update_wrapper` as a
514 function decorator when defining a wrapper function. It is equivalent to
515 ``partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)``.
516 For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000517
Christian Heimesfe337bf2008-03-23 21:54:12 +0000518 >>> from functools import wraps
Georg Brandl116aa622007-08-15 14:28:22 +0000519 >>> def my_decorator(f):
520 ... @wraps(f)
521 ... def wrapper(*args, **kwds):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000522 ... print('Calling decorated function')
Georg Brandl116aa622007-08-15 14:28:22 +0000523 ... return f(*args, **kwds)
524 ... return wrapper
525 ...
526 >>> @my_decorator
527 ... def example():
528 ... """Docstring"""
Georg Brandl6911e3c2007-09-04 07:15:32 +0000529 ... print('Called example function')
Georg Brandl116aa622007-08-15 14:28:22 +0000530 ...
531 >>> example()
532 Calling decorated function
533 Called example function
534 >>> example.__name__
535 'example'
536 >>> example.__doc__
537 'Docstring'
538
539 Without the use of this decorator factory, the name of the example function
540 would have been ``'wrapper'``, and the docstring of the original :func:`example`
541 would have been lost.
542
543
544.. _partial-objects:
545
546:class:`partial` Objects
547------------------------
548
549:class:`partial` objects are callable objects created by :func:`partial`. They
550have three read-only attributes:
551
552
553.. attribute:: partial.func
554
555 A callable object or function. Calls to the :class:`partial` object will be
556 forwarded to :attr:`func` with new arguments and keywords.
557
558
559.. attribute:: partial.args
560
561 The leftmost positional arguments that will be prepended to the positional
562 arguments provided to a :class:`partial` object call.
563
564
565.. attribute:: partial.keywords
566
567 The keyword arguments that will be supplied when the :class:`partial` object is
568 called.
569
570:class:`partial` objects are like :class:`function` objects in that they are
571callable, weak referencable, and can have attributes. There are some important
Martin Panterbae5d812016-06-18 03:57:31 +0000572differences. For instance, the :attr:`~definition.__name__` and :attr:`__doc__` attributes
Georg Brandl116aa622007-08-15 14:28:22 +0000573are not created automatically. Also, :class:`partial` objects defined in
574classes behave like static methods and do not transform into bound methods
575during instance attribute look-up.