blob: 8924593464f9cf1a5097d6ea7262d20010bd5cb8 [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
Éric Araujob10089e2010-11-18 14:22:08 +000023.. function:: cmp_to_key(func)
Raymond Hettingerc50846a2010-04-05 18:56:31 +000024
Raymond Hettinger86e9b6b2014-11-09 17:20:56 -080025 Transform an old-style comparison function to a :term:`key function`. Used
26 with tools that accept key functions (such as :func:`sorted`, :func:`min`,
Benjamin Petersoncca65312010-08-09 02:13:10 +000027 :func:`max`, :func:`heapq.nlargest`, :func:`heapq.nsmallest`,
28 :func:`itertools.groupby`). This function is primarily used as a transition
Ezio Melotti9ecb6be2012-01-16 08:28:54 +020029 tool for programs being converted from Python 2 which supported the use of
Benjamin Petersoncca65312010-08-09 02:13:10 +000030 comparison functions.
Raymond Hettingerc50846a2010-04-05 18:56:31 +000031
Georg Brandl6c89a792012-01-25 22:36:25 +010032 A comparison function is any callable that accept two arguments, compares them,
Benjamin Petersoncca65312010-08-09 02:13:10 +000033 and returns a negative number for less-than, zero for equality, or a positive
34 number for greater-than. A key function is a callable that accepts one
Raymond Hettinger86e9b6b2014-11-09 17:20:56 -080035 argument and returns another value to be used as the sort key.
Raymond Hettingerc50846a2010-04-05 18:56:31 +000036
Benjamin Petersoncca65312010-08-09 02:13:10 +000037 Example::
Raymond Hettingerc50846a2010-04-05 18:56:31 +000038
Benjamin Petersoncca65312010-08-09 02:13:10 +000039 sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order
Raymond Hettingerc50846a2010-04-05 18:56:31 +000040
Raymond Hettinger86e9b6b2014-11-09 17:20:56 -080041 For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`.
42
Raymond Hettingerc50846a2010-04-05 18:56:31 +000043 .. versionadded:: 3.2
44
Georg Brandl67b21b72010-08-17 15:07:14 +000045
Raymond Hettinger010ce322012-05-19 21:20:48 -070046.. decorator:: lru_cache(maxsize=128, typed=False)
Georg Brandl2e7346a2010-07-31 18:09:23 +000047
48 Decorator to wrap a function with a memoizing callable that saves up to the
49 *maxsize* most recent calls. It can save time when an expensive or I/O bound
50 function is periodically called with the same arguments.
51
Raymond Hettinger7496b412010-11-30 19:15:45 +000052 Since a dictionary is used to cache results, the positional and keyword
53 arguments to the function must be hashable.
Georg Brandl2e7346a2010-07-31 18:09:23 +000054
Miss Islington (bot)a8f189f2018-09-14 01:13:17 -070055 Distinct argument patterns may be considered to be distinct calls with
56 separate cache entries. For example, `f(a=1, b=2)` and `f(b=2, a=1)`
57 differ in their keyword argument order and may have two separate cache
58 entries.
59
Serhiy Storchakaecf41da2016-10-19 16:29:26 +030060 If *maxsize* is set to ``None``, the LRU feature is disabled and the cache can
Raymond Hettinger7d74eff2012-06-04 00:32:15 -070061 grow without bound. The LRU feature performs best when *maxsize* is a
62 power-of-two.
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +000063
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +030064 If *typed* is set to true, function arguments of different types will be
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -070065 cached separately. For example, ``f(3)`` and ``f(3.0)`` will be treated
66 as distinct calls with distinct results.
67
Raymond Hettinger7496b412010-11-30 19:15:45 +000068 To help measure the effectiveness of the cache and tune the *maxsize*
69 parameter, the wrapped function is instrumented with a :func:`cache_info`
70 function that returns a :term:`named tuple` showing *hits*, *misses*,
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +000071 *maxsize* and *currsize*. In a multi-threaded environment, the hits
72 and misses are approximate.
Nick Coghlan234515a2010-11-30 06:19:46 +000073
Raymond Hettinger7496b412010-11-30 19:15:45 +000074 The decorator also provides a :func:`cache_clear` function for clearing or
75 invalidating the cache.
Georg Brandl2e7346a2010-07-31 18:09:23 +000076
Raymond Hettinger3fccfcb2010-08-17 19:19:29 +000077 The original underlying function is accessible through the
Raymond Hettinger7496b412010-11-30 19:15:45 +000078 :attr:`__wrapped__` attribute. This is useful for introspection, for
79 bypassing the cache, or for rewrapping the function with a different cache.
Nick Coghlan98876832010-08-17 06:17:18 +000080
Raymond Hettingercc038582010-11-30 20:02:57 +000081 An `LRU (least recently used) cache
Georg Brandl5d941342016-02-26 19:37:12 +010082 <https://en.wikipedia.org/wiki/Cache_algorithms#Examples>`_ works
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -070083 best when the most recent calls are the best predictors of upcoming calls (for
84 example, the most popular articles on a news server tend to change each day).
Raymond Hettinger7496b412010-11-30 19:15:45 +000085 The cache's size limit assures that the cache does not grow without bound on
86 long-running processes such as web servers.
87
Raymond Hettingercc038582010-11-30 20:02:57 +000088 Example of an LRU cache for static web content::
Raymond Hettinger7496b412010-11-30 19:15:45 +000089
Raymond Hettinger17328e42013-04-06 20:27:33 -070090 @lru_cache(maxsize=32)
Raymond Hettinger7496b412010-11-30 19:15:45 +000091 def get_pep(num):
92 'Retrieve text of a Python Enhancement Proposal'
93 resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
94 try:
95 with urllib.request.urlopen(resource) as s:
96 return s.read()
97 except urllib.error.HTTPError:
98 return 'Not Found'
99
100 >>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
101 ... pep = get_pep(n)
102 ... print(n, len(pep))
103
Raymond Hettinger17328e42013-04-06 20:27:33 -0700104 >>> get_pep.cache_info()
105 CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
Georg Brandl2e7346a2010-07-31 18:09:23 +0000106
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000107 Example of efficiently computing
Georg Brandl5d941342016-02-26 19:37:12 +0100108 `Fibonacci numbers <https://en.wikipedia.org/wiki/Fibonacci_number>`_
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000109 using a cache to implement a
Georg Brandl5d941342016-02-26 19:37:12 +0100110 `dynamic programming <https://en.wikipedia.org/wiki/Dynamic_programming>`_
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000111 technique::
112
113 @lru_cache(maxsize=None)
114 def fib(n):
115 if n < 2:
116 return n
117 return fib(n-1) + fib(n-2)
118
Raymond Hettinger17328e42013-04-06 20:27:33 -0700119 >>> [fib(n) for n in range(16)]
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000120 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
121
Raymond Hettinger17328e42013-04-06 20:27:33 -0700122 >>> fib.cache_info()
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000123 CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
124
Georg Brandl2e7346a2010-07-31 18:09:23 +0000125 .. versionadded:: 3.2
126
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -0700127 .. versionchanged:: 3.3
128 Added the *typed* option.
129
Georg Brandl8a1caa22010-07-29 16:01:11 +0000130.. decorator:: total_ordering
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000131
132 Given a class defining one or more rich comparison ordering methods, this
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000133 class decorator supplies the rest. This simplifies the effort involved
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000134 in specifying all of the possible rich comparison operations:
135
136 The class must define one of :meth:`__lt__`, :meth:`__le__`,
137 :meth:`__gt__`, or :meth:`__ge__`.
138 In addition, the class should supply an :meth:`__eq__` method.
139
140 For example::
141
142 @total_ordering
143 class Student:
Nick Coghlanf05d9812013-10-02 00:02:03 +1000144 def _is_valid_operand(self, other):
145 return (hasattr(other, "lastname") and
146 hasattr(other, "firstname"))
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000147 def __eq__(self, other):
Nick Coghlanf05d9812013-10-02 00:02:03 +1000148 if not self._is_valid_operand(other):
149 return NotImplemented
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000150 return ((self.lastname.lower(), self.firstname.lower()) ==
151 (other.lastname.lower(), other.firstname.lower()))
152 def __lt__(self, other):
Nick Coghlanf05d9812013-10-02 00:02:03 +1000153 if not self._is_valid_operand(other):
154 return NotImplemented
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000155 return ((self.lastname.lower(), self.firstname.lower()) <
156 (other.lastname.lower(), other.firstname.lower()))
157
Nick Coghlanf05d9812013-10-02 00:02:03 +1000158 .. note::
159
160 While this decorator makes it easy to create well behaved totally
161 ordered types, it *does* come at the cost of slower execution and
162 more complex stack traces for the derived comparison methods. If
163 performance benchmarking indicates this is a bottleneck for a given
164 application, implementing all six rich comparison methods instead is
165 likely to provide an easy speed boost.
166
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000167 .. versionadded:: 3.2
168
Nick Coghlanf05d9812013-10-02 00:02:03 +1000169 .. versionchanged:: 3.4
170 Returning NotImplemented from the underlying comparison function for
171 unrecognised types is now supported.
Georg Brandl67b21b72010-08-17 15:07:14 +0000172
Georg Brandl036490d2009-05-17 13:00:36 +0000173.. function:: partial(func, *args, **keywords)
Georg Brandl116aa622007-08-15 14:28:22 +0000174
Miss Islington (bot)fc62c722018-10-22 23:16:42 -0700175 Return a new :ref:`partial object<partial-objects>` which when called
176 will behave like *func* called with the positional arguments *args*
177 and keyword arguments *keywords*. If more arguments are supplied to the
178 call, they are appended to *args*. If additional keyword arguments are
179 supplied, they extend and override *keywords*.
Georg Brandl116aa622007-08-15 14:28:22 +0000180 Roughly equivalent to::
181
182 def partial(func, *args, **keywords):
183 def newfunc(*fargs, **fkeywords):
184 newkeywords = keywords.copy()
185 newkeywords.update(fkeywords)
Martin Panter0c0da482016-06-12 01:46:50 +0000186 return func(*args, *fargs, **newkeywords)
Georg Brandl116aa622007-08-15 14:28:22 +0000187 newfunc.func = func
188 newfunc.args = args
189 newfunc.keywords = keywords
190 return newfunc
191
192 The :func:`partial` is used for partial function application which "freezes"
193 some portion of a function's arguments and/or keywords resulting in a new object
194 with a simplified signature. For example, :func:`partial` can be used to create
195 a callable that behaves like the :func:`int` function where the *base* argument
Christian Heimesfe337bf2008-03-23 21:54:12 +0000196 defaults to two:
Georg Brandl116aa622007-08-15 14:28:22 +0000197
Christian Heimesfe337bf2008-03-23 21:54:12 +0000198 >>> from functools import partial
Georg Brandl116aa622007-08-15 14:28:22 +0000199 >>> basetwo = partial(int, base=2)
200 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
201 >>> basetwo('10010')
202 18
203
204
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000205.. class:: partialmethod(func, *args, **keywords)
206
207 Return a new :class:`partialmethod` descriptor which behaves
208 like :class:`partial` except that it is designed to be used as a method
209 definition rather than being directly callable.
210
211 *func* must be a :term:`descriptor` or a callable (objects which are both,
212 like normal functions, are handled as descriptors).
213
214 When *func* is a descriptor (such as a normal Python function,
215 :func:`classmethod`, :func:`staticmethod`, :func:`abstractmethod` or
216 another instance of :class:`partialmethod`), calls to ``__get__`` are
217 delegated to the underlying descriptor, and an appropriate
Miss Islington (bot)fc62c722018-10-22 23:16:42 -0700218 :ref:`partial object<partial-objects>` returned as the result.
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000219
220 When *func* is a non-descriptor callable, an appropriate bound method is
221 created dynamically. This behaves like a normal Python function when
222 used as a method: the *self* argument will be inserted as the first
223 positional argument, even before the *args* and *keywords* supplied to
224 the :class:`partialmethod` constructor.
225
226 Example::
227
228 >>> class Cell(object):
Benjamin Peterson3a434032014-03-30 15:07:09 -0400229 ... def __init__(self):
230 ... self._alive = False
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000231 ... @property
232 ... def alive(self):
233 ... return self._alive
234 ... def set_state(self, state):
235 ... self._alive = bool(state)
Nick Coghlan3daaf5f2013-11-04 23:32:16 +1000236 ... set_alive = partialmethod(set_state, True)
237 ... set_dead = partialmethod(set_state, False)
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000238 ...
239 >>> c = Cell()
240 >>> c.alive
241 False
242 >>> c.set_alive()
243 >>> c.alive
244 True
245
246 .. versionadded:: 3.4
247
248
Georg Brandl58f9e4f2008-04-19 22:18:33 +0000249.. function:: reduce(function, iterable[, initializer])
Georg Brandl116aa622007-08-15 14:28:22 +0000250
251 Apply *function* of two arguments cumulatively to the items of *sequence*, from
252 left to right, so as to reduce the sequence to a single value. For example,
253 ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``.
254 The left argument, *x*, is the accumulated value and the right argument, *y*, is
255 the update value from the *sequence*. If the optional *initializer* is present,
256 it is placed before the items of the sequence in the calculation, and serves as
257 a default when the sequence is empty. If *initializer* is not given and
258 *sequence* contains only one item, the first item is returned.
259
Raymond Hettinger558dcf32014-12-16 18:16:57 -0800260 Roughly equivalent to::
Raymond Hettinger64801682013-10-12 16:04:17 -0700261
262 def reduce(function, iterable, initializer=None):
263 it = iter(iterable)
264 if initializer is None:
265 value = next(it)
266 else:
267 value = initializer
268 for element in it:
269 value = function(value, element)
270 return value
271
Georg Brandl116aa622007-08-15 14:28:22 +0000272
Daisuke Miyakawa0e61e672017-10-12 23:39:43 +0900273.. decorator:: singledispatch
Łukasz Langa6f692512013-06-05 12:20:24 +0200274
Daisuke Miyakawa0e61e672017-10-12 23:39:43 +0900275 Transform a function into a :term:`single-dispatch <single
Łukasz Langafdcf2b72013-06-07 22:54:03 +0200276 dispatch>` :term:`generic function`.
Łukasz Langa6f692512013-06-05 12:20:24 +0200277
278 To define a generic function, decorate it with the ``@singledispatch``
279 decorator. Note that the dispatch happens on the type of the first argument,
280 create your function accordingly::
281
282 >>> from functools import singledispatch
283 >>> @singledispatch
284 ... def fun(arg, verbose=False):
285 ... if verbose:
286 ... print("Let me just say,", end=" ")
287 ... print(arg)
288
289 To add overloaded implementations to the function, use the :func:`register`
Łukasz Langae5697532017-12-11 13:56:31 -0800290 attribute of the generic function. It is a decorator. For functions
291 annotated with types, the decorator will infer the type of the first
292 argument automatically::
Łukasz Langa6f692512013-06-05 12:20:24 +0200293
Łukasz Langae5697532017-12-11 13:56:31 -0800294 >>> @fun.register
295 ... def _(arg: int, verbose=False):
Łukasz Langa6f692512013-06-05 12:20:24 +0200296 ... if verbose:
297 ... print("Strength in numbers, eh?", end=" ")
298 ... print(arg)
299 ...
Łukasz Langae5697532017-12-11 13:56:31 -0800300 >>> @fun.register
301 ... def _(arg: list, verbose=False):
Łukasz Langa6f692512013-06-05 12:20:24 +0200302 ... if verbose:
303 ... print("Enumerate this:")
304 ... for i, elem in enumerate(arg):
305 ... print(i, elem)
306
Łukasz Langae5697532017-12-11 13:56:31 -0800307 For code which doesn't use type annotations, the appropriate type
308 argument can be passed explicitly to the decorator itself::
309
310 >>> @fun.register(complex)
311 ... def _(arg, verbose=False):
312 ... if verbose:
313 ... print("Better than complicated.", end=" ")
314 ... print(arg.real, arg.imag)
315 ...
316
317
Łukasz Langa6f692512013-06-05 12:20:24 +0200318 To enable registering lambdas and pre-existing functions, the
319 :func:`register` attribute can be used in a functional form::
320
321 >>> def nothing(arg, verbose=False):
322 ... print("Nothing.")
323 ...
324 >>> fun.register(type(None), nothing)
325
326 The :func:`register` attribute returns the undecorated function which
327 enables decorator stacking, pickling, as well as creating unit tests for
328 each variant independently::
329
330 >>> @fun.register(float)
331 ... @fun.register(Decimal)
332 ... def fun_num(arg, verbose=False):
333 ... if verbose:
334 ... print("Half of your number:", end=" ")
335 ... print(arg / 2)
336 ...
337 >>> fun_num is fun
338 False
339
340 When called, the generic function dispatches on the type of the first
341 argument::
342
343 >>> fun("Hello, world.")
344 Hello, world.
345 >>> fun("test.", verbose=True)
346 Let me just say, test.
347 >>> fun(42, verbose=True)
348 Strength in numbers, eh? 42
349 >>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)
350 Enumerate this:
351 0 spam
352 1 spam
353 2 eggs
354 3 spam
355 >>> fun(None)
356 Nothing.
357 >>> fun(1.23)
358 0.615
359
360 Where there is no registered implementation for a specific type, its
361 method resolution order is used to find a more generic implementation.
362 The original function decorated with ``@singledispatch`` is registered
363 for the base ``object`` type, which means it is used if no better
364 implementation is found.
365
366 To check which implementation will the generic function choose for
367 a given type, use the ``dispatch()`` attribute::
368
369 >>> fun.dispatch(float)
370 <function fun_num at 0x1035a2840>
371 >>> fun.dispatch(dict) # note: default implementation
372 <function fun at 0x103fe0000>
373
374 To access all registered implementations, use the read-only ``registry``
375 attribute::
376
377 >>> fun.registry.keys()
378 dict_keys([<class 'NoneType'>, <class 'int'>, <class 'object'>,
379 <class 'decimal.Decimal'>, <class 'list'>,
380 <class 'float'>])
381 >>> fun.registry[float]
382 <function fun_num at 0x1035a2840>
383 >>> fun.registry[object]
384 <function fun at 0x103fe0000>
385
386 .. versionadded:: 3.4
387
Łukasz Langae5697532017-12-11 13:56:31 -0800388 .. versionchanged:: 3.7
389 The :func:`register` attribute supports using type annotations.
390
Łukasz Langa6f692512013-06-05 12:20:24 +0200391
Georg Brandl036490d2009-05-17 13:00:36 +0000392.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000393
394 Update a *wrapper* function to look like the *wrapped* function. The optional
395 arguments are tuples to specify which attributes of the original function are
396 assigned directly to the matching attributes on the wrapper function and which
397 attributes of the wrapper function are updated with the corresponding attributes
398 from the original function. The default values for these arguments are the
Berker Peksag472233e2016-04-18 21:20:50 +0300399 module level constants ``WRAPPER_ASSIGNMENTS`` (which assigns to the wrapper
400 function's ``__module__``, ``__name__``, ``__qualname__``, ``__annotations__``
401 and ``__doc__``, the documentation string) and ``WRAPPER_UPDATES`` (which
402 updates the wrapper function's ``__dict__``, i.e. the instance dictionary).
Georg Brandl116aa622007-08-15 14:28:22 +0000403
Nick Coghlan98876832010-08-17 06:17:18 +0000404 To allow access to the original function for introspection and other purposes
405 (e.g. bypassing a caching decorator such as :func:`lru_cache`), this function
Nick Coghlan24c05bc2013-07-15 21:13:08 +1000406 automatically adds a ``__wrapped__`` attribute to the wrapper that refers to
407 the function being wrapped.
Nick Coghlan98876832010-08-17 06:17:18 +0000408
Christian Heimesd8654cf2007-12-02 15:22:16 +0000409 The main intended use for this function is in :term:`decorator` functions which
410 wrap the decorated function and return the wrapper. If the wrapper function is
411 not updated, the metadata of the returned function will reflect the wrapper
Georg Brandl116aa622007-08-15 14:28:22 +0000412 definition rather than the original function definition, which is typically less
413 than helpful.
414
Nick Coghlan98876832010-08-17 06:17:18 +0000415 :func:`update_wrapper` may be used with callables other than functions. Any
416 attributes named in *assigned* or *updated* that are missing from the object
417 being wrapped are ignored (i.e. this function will not attempt to set them
418 on the wrapper function). :exc:`AttributeError` is still raised if the
419 wrapper function itself is missing any attributes named in *updated*.
420
421 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000422 Automatic addition of the ``__wrapped__`` attribute.
Nick Coghlan98876832010-08-17 06:17:18 +0000423
424 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000425 Copying of the ``__annotations__`` attribute by default.
Nick Coghlan98876832010-08-17 06:17:18 +0000426
427 .. versionchanged:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000428 Missing attributes no longer trigger an :exc:`AttributeError`.
429
Nick Coghlan24c05bc2013-07-15 21:13:08 +1000430 .. versionchanged:: 3.4
431 The ``__wrapped__`` attribute now always refers to the wrapped
432 function, even if that function defined a ``__wrapped__`` attribute.
433 (see :issue:`17482`)
434
Georg Brandl116aa622007-08-15 14:28:22 +0000435
Georg Brandl8a1caa22010-07-29 16:01:11 +0000436.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000437
Ezio Melotti67f6d5f2014-08-05 08:14:28 +0300438 This is a convenience function for invoking :func:`update_wrapper` as a
439 function decorator when defining a wrapper function. It is equivalent to
440 ``partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)``.
441 For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000442
Christian Heimesfe337bf2008-03-23 21:54:12 +0000443 >>> from functools import wraps
Georg Brandl116aa622007-08-15 14:28:22 +0000444 >>> def my_decorator(f):
445 ... @wraps(f)
446 ... def wrapper(*args, **kwds):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000447 ... print('Calling decorated function')
Georg Brandl116aa622007-08-15 14:28:22 +0000448 ... return f(*args, **kwds)
449 ... return wrapper
450 ...
451 >>> @my_decorator
452 ... def example():
453 ... """Docstring"""
Georg Brandl6911e3c2007-09-04 07:15:32 +0000454 ... print('Called example function')
Georg Brandl116aa622007-08-15 14:28:22 +0000455 ...
456 >>> example()
457 Calling decorated function
458 Called example function
459 >>> example.__name__
460 'example'
461 >>> example.__doc__
462 'Docstring'
463
464 Without the use of this decorator factory, the name of the example function
465 would have been ``'wrapper'``, and the docstring of the original :func:`example`
466 would have been lost.
467
468
469.. _partial-objects:
470
471:class:`partial` Objects
472------------------------
473
474:class:`partial` objects are callable objects created by :func:`partial`. They
475have three read-only attributes:
476
477
478.. attribute:: partial.func
479
480 A callable object or function. Calls to the :class:`partial` object will be
481 forwarded to :attr:`func` with new arguments and keywords.
482
483
484.. attribute:: partial.args
485
486 The leftmost positional arguments that will be prepended to the positional
487 arguments provided to a :class:`partial` object call.
488
489
490.. attribute:: partial.keywords
491
492 The keyword arguments that will be supplied when the :class:`partial` object is
493 called.
494
495:class:`partial` objects are like :class:`function` objects in that they are
496callable, weak referencable, and can have attributes. There are some important
Martin Panterbae5d812016-06-18 03:57:31 +0000497differences. For instance, the :attr:`~definition.__name__` and :attr:`__doc__` attributes
Georg Brandl116aa622007-08-15 14:28:22 +0000498are not created automatically. Also, :class:`partial` objects defined in
499classes behave like static methods and do not transform into bound methods
500during instance attribute look-up.