blob: 3a0b554e923c7a62c639a0f770bbcd940792d0be [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 Hettingerb8218682019-05-26 11:27:35 -070079.. decorator:: lru_cache(user_function)
80 lru_cache(maxsize=128, typed=False)
Georg Brandl2e7346a2010-07-31 18:09:23 +000081
82 Decorator to wrap a function with a memoizing callable that saves up to the
83 *maxsize* most recent calls. It can save time when an expensive or I/O bound
84 function is periodically called with the same arguments.
85
Raymond Hettinger7496b412010-11-30 19:15:45 +000086 Since a dictionary is used to cache results, the positional and keyword
87 arguments to the function must be hashable.
Georg Brandl2e7346a2010-07-31 18:09:23 +000088
Raymond Hettinger902bcd92018-09-14 00:53:20 -070089 Distinct argument patterns may be considered to be distinct calls with
90 separate cache entries. For example, `f(a=1, b=2)` and `f(b=2, a=1)`
91 differ in their keyword argument order and may have two separate cache
92 entries.
93
Raymond Hettingerb8218682019-05-26 11:27:35 -070094 If *user_function* is specified, it must be a callable. This allows the
95 *lru_cache* decorator to be applied directly to a user function, leaving
96 the *maxsize* at its default value of 128::
97
98 @lru_cache
99 def count_vowels(sentence):
100 sentence = sentence.casefold()
101 return sum(sentence.count(vowel) for vowel in 'aeiou')
102
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300103 If *maxsize* is set to ``None``, the LRU feature is disabled and the cache can
Raymond Hettinger7d74eff2012-06-04 00:32:15 -0700104 grow without bound. The LRU feature performs best when *maxsize* is a
105 power-of-two.
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000106
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300107 If *typed* is set to true, function arguments of different types will be
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -0700108 cached separately. For example, ``f(3)`` and ``f(3.0)`` will be treated
109 as distinct calls with distinct results.
110
Raymond Hettinger7496b412010-11-30 19:15:45 +0000111 To help measure the effectiveness of the cache and tune the *maxsize*
112 parameter, the wrapped function is instrumented with a :func:`cache_info`
113 function that returns a :term:`named tuple` showing *hits*, *misses*,
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000114 *maxsize* and *currsize*. In a multi-threaded environment, the hits
115 and misses are approximate.
Nick Coghlan234515a2010-11-30 06:19:46 +0000116
Raymond Hettinger7496b412010-11-30 19:15:45 +0000117 The decorator also provides a :func:`cache_clear` function for clearing or
118 invalidating the cache.
Georg Brandl2e7346a2010-07-31 18:09:23 +0000119
Raymond Hettinger3fccfcb2010-08-17 19:19:29 +0000120 The original underlying function is accessible through the
Raymond Hettinger7496b412010-11-30 19:15:45 +0000121 :attr:`__wrapped__` attribute. This is useful for introspection, for
122 bypassing the cache, or for rewrapping the function with a different cache.
Nick Coghlan98876832010-08-17 06:17:18 +0000123
Raymond Hettingercc038582010-11-30 20:02:57 +0000124 An `LRU (least recently used) cache
Georg Brandl5d941342016-02-26 19:37:12 +0100125 <https://en.wikipedia.org/wiki/Cache_algorithms#Examples>`_ works
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -0700126 best when the most recent calls are the best predictors of upcoming calls (for
127 example, the most popular articles on a news server tend to change each day).
Raymond Hettinger7496b412010-11-30 19:15:45 +0000128 The cache's size limit assures that the cache does not grow without bound on
129 long-running processes such as web servers.
130
Raymond Hettingerf0e0f202018-11-25 16:24:52 -0800131 In general, the LRU cache should only be used when you want to reuse
132 previously computed values. Accordingly, it doesn't make sense to cache
133 functions with side-effects, functions that need to create distinct mutable
134 objects on each call, or impure functions such as time() or random().
135
Raymond Hettingercc038582010-11-30 20:02:57 +0000136 Example of an LRU cache for static web content::
Raymond Hettinger7496b412010-11-30 19:15:45 +0000137
Raymond Hettinger17328e42013-04-06 20:27:33 -0700138 @lru_cache(maxsize=32)
Raymond Hettinger7496b412010-11-30 19:15:45 +0000139 def get_pep(num):
140 'Retrieve text of a Python Enhancement Proposal'
141 resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
142 try:
143 with urllib.request.urlopen(resource) as s:
144 return s.read()
145 except urllib.error.HTTPError:
146 return 'Not Found'
147
148 >>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
149 ... pep = get_pep(n)
150 ... print(n, len(pep))
151
Raymond Hettinger17328e42013-04-06 20:27:33 -0700152 >>> get_pep.cache_info()
153 CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
Georg Brandl2e7346a2010-07-31 18:09:23 +0000154
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000155 Example of efficiently computing
Georg Brandl5d941342016-02-26 19:37:12 +0100156 `Fibonacci numbers <https://en.wikipedia.org/wiki/Fibonacci_number>`_
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000157 using a cache to implement a
Georg Brandl5d941342016-02-26 19:37:12 +0100158 `dynamic programming <https://en.wikipedia.org/wiki/Dynamic_programming>`_
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000159 technique::
160
161 @lru_cache(maxsize=None)
162 def fib(n):
163 if n < 2:
164 return n
165 return fib(n-1) + fib(n-2)
166
Raymond Hettinger17328e42013-04-06 20:27:33 -0700167 >>> [fib(n) for n in range(16)]
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000168 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
169
Raymond Hettinger17328e42013-04-06 20:27:33 -0700170 >>> fib.cache_info()
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000171 CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
172
Georg Brandl2e7346a2010-07-31 18:09:23 +0000173 .. versionadded:: 3.2
174
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -0700175 .. versionchanged:: 3.3
176 Added the *typed* option.
177
Raymond Hettingerb8218682019-05-26 11:27:35 -0700178 .. versionchanged:: 3.8
179 Added the *user_function* option.
180
Georg Brandl8a1caa22010-07-29 16:01:11 +0000181.. decorator:: total_ordering
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000182
183 Given a class defining one or more rich comparison ordering methods, this
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000184 class decorator supplies the rest. This simplifies the effort involved
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000185 in specifying all of the possible rich comparison operations:
186
187 The class must define one of :meth:`__lt__`, :meth:`__le__`,
188 :meth:`__gt__`, or :meth:`__ge__`.
189 In addition, the class should supply an :meth:`__eq__` method.
190
191 For example::
192
193 @total_ordering
194 class Student:
Nick Coghlanf05d9812013-10-02 00:02:03 +1000195 def _is_valid_operand(self, other):
196 return (hasattr(other, "lastname") and
197 hasattr(other, "firstname"))
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000198 def __eq__(self, other):
Nick Coghlanf05d9812013-10-02 00:02:03 +1000199 if not self._is_valid_operand(other):
200 return NotImplemented
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000201 return ((self.lastname.lower(), self.firstname.lower()) ==
202 (other.lastname.lower(), other.firstname.lower()))
203 def __lt__(self, other):
Nick Coghlanf05d9812013-10-02 00:02:03 +1000204 if not self._is_valid_operand(other):
205 return NotImplemented
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000206 return ((self.lastname.lower(), self.firstname.lower()) <
207 (other.lastname.lower(), other.firstname.lower()))
208
Nick Coghlanf05d9812013-10-02 00:02:03 +1000209 .. note::
210
211 While this decorator makes it easy to create well behaved totally
212 ordered types, it *does* come at the cost of slower execution and
213 more complex stack traces for the derived comparison methods. If
214 performance benchmarking indicates this is a bottleneck for a given
215 application, implementing all six rich comparison methods instead is
216 likely to provide an easy speed boost.
217
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000218 .. versionadded:: 3.2
219
Nick Coghlanf05d9812013-10-02 00:02:03 +1000220 .. versionchanged:: 3.4
221 Returning NotImplemented from the underlying comparison function for
222 unrecognised types is now supported.
Georg Brandl67b21b72010-08-17 15:07:14 +0000223
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300224.. function:: partial(func, /, *args, **keywords)
Georg Brandl116aa622007-08-15 14:28:22 +0000225
Andrei Petre83a07652018-10-22 23:11:20 -0700226 Return a new :ref:`partial object<partial-objects>` which when called
227 will behave like *func* called with the positional arguments *args*
228 and keyword arguments *keywords*. If more arguments are supplied to the
229 call, they are appended to *args*. If additional keyword arguments are
230 supplied, they extend and override *keywords*.
Georg Brandl116aa622007-08-15 14:28:22 +0000231 Roughly equivalent to::
232
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300233 def partial(func, /, *args, **keywords):
Georg Brandl116aa622007-08-15 14:28:22 +0000234 def newfunc(*fargs, **fkeywords):
Sergey Fedoseevb981fec2018-10-20 02:42:07 +0500235 newkeywords = {**keywords, **fkeywords}
Martin Panter0c0da482016-06-12 01:46:50 +0000236 return func(*args, *fargs, **newkeywords)
Georg Brandl116aa622007-08-15 14:28:22 +0000237 newfunc.func = func
238 newfunc.args = args
239 newfunc.keywords = keywords
240 return newfunc
241
242 The :func:`partial` is used for partial function application which "freezes"
243 some portion of a function's arguments and/or keywords resulting in a new object
244 with a simplified signature. For example, :func:`partial` can be used to create
245 a callable that behaves like the :func:`int` function where the *base* argument
Christian Heimesfe337bf2008-03-23 21:54:12 +0000246 defaults to two:
Georg Brandl116aa622007-08-15 14:28:22 +0000247
Christian Heimesfe337bf2008-03-23 21:54:12 +0000248 >>> from functools import partial
Georg Brandl116aa622007-08-15 14:28:22 +0000249 >>> basetwo = partial(int, base=2)
250 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
251 >>> basetwo('10010')
252 18
253
254
Serhiy Storchaka70c5f2a2019-06-01 11:38:24 +0300255.. class:: partialmethod(func, /, *args, **keywords)
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000256
257 Return a new :class:`partialmethod` descriptor which behaves
258 like :class:`partial` except that it is designed to be used as a method
259 definition rather than being directly callable.
260
261 *func* must be a :term:`descriptor` or a callable (objects which are both,
262 like normal functions, are handled as descriptors).
263
264 When *func* is a descriptor (such as a normal Python function,
265 :func:`classmethod`, :func:`staticmethod`, :func:`abstractmethod` or
266 another instance of :class:`partialmethod`), calls to ``__get__`` are
267 delegated to the underlying descriptor, and an appropriate
Andrei Petre83a07652018-10-22 23:11:20 -0700268 :ref:`partial object<partial-objects>` returned as the result.
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000269
270 When *func* is a non-descriptor callable, an appropriate bound method is
271 created dynamically. This behaves like a normal Python function when
272 used as a method: the *self* argument will be inserted as the first
273 positional argument, even before the *args* and *keywords* supplied to
274 the :class:`partialmethod` constructor.
275
276 Example::
277
278 >>> class Cell(object):
Benjamin Peterson3a434032014-03-30 15:07:09 -0400279 ... def __init__(self):
280 ... self._alive = False
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000281 ... @property
282 ... def alive(self):
283 ... return self._alive
284 ... def set_state(self, state):
285 ... self._alive = bool(state)
Nick Coghlan3daaf5f2013-11-04 23:32:16 +1000286 ... set_alive = partialmethod(set_state, True)
287 ... set_dead = partialmethod(set_state, False)
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000288 ...
289 >>> c = Cell()
290 >>> c.alive
291 False
292 >>> c.set_alive()
293 >>> c.alive
294 True
295
296 .. versionadded:: 3.4
297
298
Georg Brandl58f9e4f2008-04-19 22:18:33 +0000299.. function:: reduce(function, iterable[, initializer])
Georg Brandl116aa622007-08-15 14:28:22 +0000300
Brendan Jurd9df10022018-10-01 16:52:10 +1000301 Apply *function* of two arguments cumulatively to the items of *iterable*, from
302 left to right, so as to reduce the iterable to a single value. For example,
Georg Brandl116aa622007-08-15 14:28:22 +0000303 ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``.
304 The left argument, *x*, is the accumulated value and the right argument, *y*, is
Brendan Jurd9df10022018-10-01 16:52:10 +1000305 the update value from the *iterable*. If the optional *initializer* is present,
306 it is placed before the items of the iterable in the calculation, and serves as
307 a default when the iterable is empty. If *initializer* is not given and
308 *iterable* contains only one item, the first item is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000309
Raymond Hettinger558dcf32014-12-16 18:16:57 -0800310 Roughly equivalent to::
Raymond Hettinger64801682013-10-12 16:04:17 -0700311
312 def reduce(function, iterable, initializer=None):
313 it = iter(iterable)
314 if initializer is None:
315 value = next(it)
316 else:
317 value = initializer
318 for element in it:
319 value = function(value, element)
320 return value
321
Gerrit Hollbd81cbd2018-07-04 23:26:32 +0100322 See :func:`itertools.accumulate` for an iterator that yields all intermediate
323 values.
Georg Brandl116aa622007-08-15 14:28:22 +0000324
Daisuke Miyakawa0e61e672017-10-12 23:39:43 +0900325.. decorator:: singledispatch
Łukasz Langa6f692512013-06-05 12:20:24 +0200326
Daisuke Miyakawa0e61e672017-10-12 23:39:43 +0900327 Transform a function into a :term:`single-dispatch <single
Łukasz Langafdcf2b72013-06-07 22:54:03 +0200328 dispatch>` :term:`generic function`.
Łukasz Langa6f692512013-06-05 12:20:24 +0200329
330 To define a generic function, decorate it with the ``@singledispatch``
331 decorator. Note that the dispatch happens on the type of the first argument,
332 create your function accordingly::
333
334 >>> from functools import singledispatch
335 >>> @singledispatch
336 ... def fun(arg, verbose=False):
337 ... if verbose:
338 ... print("Let me just say,", end=" ")
339 ... print(arg)
340
341 To add overloaded implementations to the function, use the :func:`register`
Łukasz Langae5697532017-12-11 13:56:31 -0800342 attribute of the generic function. It is a decorator. For functions
343 annotated with types, the decorator will infer the type of the first
344 argument automatically::
Łukasz Langa6f692512013-06-05 12:20:24 +0200345
Łukasz Langae5697532017-12-11 13:56:31 -0800346 >>> @fun.register
347 ... def _(arg: int, verbose=False):
Łukasz Langa6f692512013-06-05 12:20:24 +0200348 ... if verbose:
349 ... print("Strength in numbers, eh?", end=" ")
350 ... print(arg)
351 ...
Łukasz Langae5697532017-12-11 13:56:31 -0800352 >>> @fun.register
353 ... def _(arg: list, verbose=False):
Łukasz Langa6f692512013-06-05 12:20:24 +0200354 ... if verbose:
355 ... print("Enumerate this:")
356 ... for i, elem in enumerate(arg):
357 ... print(i, elem)
358
Łukasz Langae5697532017-12-11 13:56:31 -0800359 For code which doesn't use type annotations, the appropriate type
360 argument can be passed explicitly to the decorator itself::
361
362 >>> @fun.register(complex)
363 ... def _(arg, verbose=False):
364 ... if verbose:
365 ... print("Better than complicated.", end=" ")
366 ... print(arg.real, arg.imag)
367 ...
368
369
Łukasz Langa6f692512013-06-05 12:20:24 +0200370 To enable registering lambdas and pre-existing functions, the
371 :func:`register` attribute can be used in a functional form::
372
373 >>> def nothing(arg, verbose=False):
374 ... print("Nothing.")
375 ...
376 >>> fun.register(type(None), nothing)
377
378 The :func:`register` attribute returns the undecorated function which
379 enables decorator stacking, pickling, as well as creating unit tests for
380 each variant independently::
381
382 >>> @fun.register(float)
383 ... @fun.register(Decimal)
384 ... def fun_num(arg, verbose=False):
385 ... if verbose:
386 ... print("Half of your number:", end=" ")
387 ... print(arg / 2)
388 ...
389 >>> fun_num is fun
390 False
391
392 When called, the generic function dispatches on the type of the first
393 argument::
394
395 >>> fun("Hello, world.")
396 Hello, world.
397 >>> fun("test.", verbose=True)
398 Let me just say, test.
399 >>> fun(42, verbose=True)
400 Strength in numbers, eh? 42
401 >>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)
402 Enumerate this:
403 0 spam
404 1 spam
405 2 eggs
406 3 spam
407 >>> fun(None)
408 Nothing.
409 >>> fun(1.23)
410 0.615
411
412 Where there is no registered implementation for a specific type, its
413 method resolution order is used to find a more generic implementation.
414 The original function decorated with ``@singledispatch`` is registered
415 for the base ``object`` type, which means it is used if no better
416 implementation is found.
417
418 To check which implementation will the generic function choose for
419 a given type, use the ``dispatch()`` attribute::
420
421 >>> fun.dispatch(float)
422 <function fun_num at 0x1035a2840>
423 >>> fun.dispatch(dict) # note: default implementation
424 <function fun at 0x103fe0000>
425
426 To access all registered implementations, use the read-only ``registry``
427 attribute::
428
429 >>> fun.registry.keys()
430 dict_keys([<class 'NoneType'>, <class 'int'>, <class 'object'>,
431 <class 'decimal.Decimal'>, <class 'list'>,
432 <class 'float'>])
433 >>> fun.registry[float]
434 <function fun_num at 0x1035a2840>
435 >>> fun.registry[object]
436 <function fun at 0x103fe0000>
437
438 .. versionadded:: 3.4
439
Łukasz Langae5697532017-12-11 13:56:31 -0800440 .. versionchanged:: 3.7
441 The :func:`register` attribute supports using type annotations.
442
Łukasz Langa6f692512013-06-05 12:20:24 +0200443
Ethan Smithc6512752018-05-26 16:38:33 -0400444.. class:: singledispatchmethod(func)
445
446 Transform a method into a :term:`single-dispatch <single
447 dispatch>` :term:`generic function`.
448
449 To define a generic method, decorate it with the ``@singledispatchmethod``
450 decorator. Note that the dispatch happens on the type of the first non-self
451 or non-cls argument, create your function accordingly::
452
453 class Negator:
454 @singledispatchmethod
455 def neg(self, arg):
456 raise NotImplementedError("Cannot negate a")
457
458 @neg.register
459 def _(self, arg: int):
460 return -arg
461
462 @neg.register
463 def _(self, arg: bool):
464 return not arg
465
466 ``@singledispatchmethod`` supports nesting with other decorators such as
467 ``@classmethod``. Note that to allow for ``dispatcher.register``,
468 ``singledispatchmethod`` must be the *outer most* decorator. Here is the
469 ``Negator`` class with the ``neg`` methods being class bound::
470
471 class Negator:
472 @singledispatchmethod
473 @classmethod
474 def neg(cls, arg):
475 raise NotImplementedError("Cannot negate a")
476
477 @neg.register
478 @classmethod
479 def _(cls, arg: int):
480 return -arg
481
482 @neg.register
483 @classmethod
484 def _(cls, arg: bool):
485 return not arg
486
487 The same pattern can be used for other similar decorators: ``staticmethod``,
488 ``abstractmethod``, and others.
489
Inada Naokibc284f02019-03-27 18:15:17 +0900490 .. versionadded:: 3.8
491
492
Georg Brandl036490d2009-05-17 13:00:36 +0000493.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000494
495 Update a *wrapper* function to look like the *wrapped* function. The optional
496 arguments are tuples to specify which attributes of the original function are
497 assigned directly to the matching attributes on the wrapper function and which
498 attributes of the wrapper function are updated with the corresponding attributes
499 from the original function. The default values for these arguments are the
Berker Peksag472233e2016-04-18 21:20:50 +0300500 module level constants ``WRAPPER_ASSIGNMENTS`` (which assigns to the wrapper
501 function's ``__module__``, ``__name__``, ``__qualname__``, ``__annotations__``
502 and ``__doc__``, the documentation string) and ``WRAPPER_UPDATES`` (which
503 updates the wrapper function's ``__dict__``, i.e. the instance dictionary).
Georg Brandl116aa622007-08-15 14:28:22 +0000504
Nick Coghlan98876832010-08-17 06:17:18 +0000505 To allow access to the original function for introspection and other purposes
506 (e.g. bypassing a caching decorator such as :func:`lru_cache`), this function
Nick Coghlan24c05bc2013-07-15 21:13:08 +1000507 automatically adds a ``__wrapped__`` attribute to the wrapper that refers to
508 the function being wrapped.
Nick Coghlan98876832010-08-17 06:17:18 +0000509
Christian Heimesd8654cf2007-12-02 15:22:16 +0000510 The main intended use for this function is in :term:`decorator` functions which
511 wrap the decorated function and return the wrapper. If the wrapper function is
512 not updated, the metadata of the returned function will reflect the wrapper
Georg Brandl116aa622007-08-15 14:28:22 +0000513 definition rather than the original function definition, which is typically less
514 than helpful.
515
Nick Coghlan98876832010-08-17 06:17:18 +0000516 :func:`update_wrapper` may be used with callables other than functions. Any
517 attributes named in *assigned* or *updated* that are missing from the object
518 being wrapped are ignored (i.e. this function will not attempt to set them
519 on the wrapper function). :exc:`AttributeError` is still raised if the
520 wrapper function itself is missing any attributes named in *updated*.
521
522 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000523 Automatic addition of the ``__wrapped__`` attribute.
Nick Coghlan98876832010-08-17 06:17:18 +0000524
525 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000526 Copying of the ``__annotations__`` attribute by default.
Nick Coghlan98876832010-08-17 06:17:18 +0000527
528 .. versionchanged:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000529 Missing attributes no longer trigger an :exc:`AttributeError`.
530
Nick Coghlan24c05bc2013-07-15 21:13:08 +1000531 .. versionchanged:: 3.4
532 The ``__wrapped__`` attribute now always refers to the wrapped
533 function, even if that function defined a ``__wrapped__`` attribute.
534 (see :issue:`17482`)
535
Georg Brandl116aa622007-08-15 14:28:22 +0000536
Georg Brandl8a1caa22010-07-29 16:01:11 +0000537.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000538
Ezio Melotti67f6d5f2014-08-05 08:14:28 +0300539 This is a convenience function for invoking :func:`update_wrapper` as a
540 function decorator when defining a wrapper function. It is equivalent to
541 ``partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)``.
542 For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000543
Christian Heimesfe337bf2008-03-23 21:54:12 +0000544 >>> from functools import wraps
Georg Brandl116aa622007-08-15 14:28:22 +0000545 >>> def my_decorator(f):
546 ... @wraps(f)
547 ... def wrapper(*args, **kwds):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000548 ... print('Calling decorated function')
Georg Brandl116aa622007-08-15 14:28:22 +0000549 ... return f(*args, **kwds)
550 ... return wrapper
551 ...
552 >>> @my_decorator
553 ... def example():
554 ... """Docstring"""
Georg Brandl6911e3c2007-09-04 07:15:32 +0000555 ... print('Called example function')
Georg Brandl116aa622007-08-15 14:28:22 +0000556 ...
557 >>> example()
558 Calling decorated function
559 Called example function
560 >>> example.__name__
561 'example'
562 >>> example.__doc__
563 'Docstring'
564
565 Without the use of this decorator factory, the name of the example function
566 would have been ``'wrapper'``, and the docstring of the original :func:`example`
567 would have been lost.
568
569
570.. _partial-objects:
571
572:class:`partial` Objects
573------------------------
574
575:class:`partial` objects are callable objects created by :func:`partial`. They
576have three read-only attributes:
577
578
579.. attribute:: partial.func
580
581 A callable object or function. Calls to the :class:`partial` object will be
582 forwarded to :attr:`func` with new arguments and keywords.
583
584
585.. attribute:: partial.args
586
587 The leftmost positional arguments that will be prepended to the positional
588 arguments provided to a :class:`partial` object call.
589
590
591.. attribute:: partial.keywords
592
593 The keyword arguments that will be supplied when the :class:`partial` object is
594 called.
595
596:class:`partial` objects are like :class:`function` objects in that they are
597callable, weak referencable, and can have attributes. There are some important
Martin Panterbae5d812016-06-18 03:57:31 +0000598differences. For instance, the :attr:`~definition.__name__` and :attr:`__doc__` attributes
Georg Brandl116aa622007-08-15 14:28:22 +0000599are not created automatically. Also, :class:`partial` objects defined in
600classes behave like static methods and do not transform into bound methods
601during instance attribute look-up.