blob: e981bcdf6f2573e20cd446684043b37b7c70dc63 [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>
Pablo Galindo99e6c262020-01-23 15:29:52 +000011.. moduleauthor:: Pablo Galindo <pablogsal@gmail.com>
Georg Brandl116aa622007-08-15 14:28:22 +000012.. sectionauthor:: Peter Harris <scav@blueyonder.co.uk>
13
Raymond Hettinger05ce0792011-01-10 21:16:07 +000014**Source code:** :source:`Lib/functools.py`
15
Pablo Galindo99e6c262020-01-23 15:29:52 +000016.. testsetup:: default
17
18 import functools
19 from functools import *
20
Raymond Hettinger05ce0792011-01-10 21:16:07 +000021--------------
Georg Brandl116aa622007-08-15 14:28:22 +000022
Georg Brandl116aa622007-08-15 14:28:22 +000023The :mod:`functools` module is for higher-order functions: functions that act on
24or return other functions. In general, any callable object can be treated as a
25function for the purposes of this module.
26
Thomas Woutersed03b412007-08-28 21:37:11 +000027The :mod:`functools` module defines the following functions:
28
Raymond Hettinger21cdb712020-05-11 17:00:53 -070029.. decorator:: cache(user_function)
30
31 Simple lightweight unbounded function cache. Sometimes called
32 `"memoize" <https://en.wikipedia.org/wiki/Memoization>`_.
33
34 Returns the same as ``lru_cache(maxsize=None)``, creating a thin
35 wrapper around a dictionary lookup for the function arguments. Because it
36 never needs to evict old values, this is smaller and faster than
37 :func:`lru_cache()` with a size limit.
38
39 For example::
40
41 @cache
42 def factorial(n):
43 return n * factorial(n-1) if n else 1
44
45 >>> factorial(10) # no previously cached result, makes 11 recursive calls
46 3628800
47 >>> factorial(5) # just looks up cached value result
48 120
49 >>> factorial(12) # makes two new recursive calls, the other 10 are cached
50 479001600
51
52 .. versionadded:: 3.9
53
54
Carl Meyerd658dea2018-08-28 01:11:56 -060055.. decorator:: cached_property(func)
56
57 Transform a method of a class into a property whose value is computed once
58 and then cached as a normal attribute for the life of the instance. Similar
59 to :func:`property`, with the addition of caching. Useful for expensive
60 computed properties of instances that are otherwise effectively immutable.
61
62 Example::
63
64 class DataSet:
Raymond Hettingerc8a7b8f2020-12-31 17:05:58 -080065
Carl Meyerd658dea2018-08-28 01:11:56 -060066 def __init__(self, sequence_of_numbers):
Raymond Hettingerc8a7b8f2020-12-31 17:05:58 -080067 self._data = tuple(sequence_of_numbers)
Carl Meyerd658dea2018-08-28 01:11:56 -060068
69 @cached_property
70 def stdev(self):
71 return statistics.stdev(self._data)
72
Raymond Hettingerc8a7b8f2020-12-31 17:05:58 -080073 The mechanics of :func:`cached_property` are somewhat different from
74 :func:`property`. A regular property blocks attribute writes unless a
75 setter is defined. In contrast, a *cached_property* allows writes.
76
77 The *cached_property* decorator only runs on lookups and only when an
78 attribute of the same name doesn't exist. When it does run, the
79 *cached_property* writes to the attribute with the same name. Subsequent
80 attribute reads and writes take precedence over the *cached_property*
81 method and it works like a normal attribute.
82
83 The cached value can be cleared by deleting the attribute. This
84 allows the *cached_property* method to run again.
Carl Meyerd658dea2018-08-28 01:11:56 -060085
Raymond Hettinger48be6b12020-10-24 18:17:17 -070086 Note, this decorator interferes with the operation of :pep:`412`
87 key-sharing dictionaries. This means that instance dictionaries
88 can take more space than usual.
89
90 Also, this decorator requires that the ``__dict__`` attribute on each instance
91 be a mutable mapping. This means it will not work with some types, such as
92 metaclasses (since the ``__dict__`` attributes on type instances are
93 read-only proxies for the class namespace), and those that specify
94 ``__slots__`` without including ``__dict__`` as one of the defined slots
95 (as such classes don't provide a ``__dict__`` attribute at all).
96
97 If a mutable mapping is not available or if space-efficient key sharing
98 is desired, an effect similar to :func:`cached_property` can be achieved
99 by a stacking :func:`property` on top of :func:`cache`::
100
101 class DataSet:
102 def __init__(self, sequence_of_numbers):
103 self._data = sequence_of_numbers
104
105 @property
106 @cache
107 def stdev(self):
108 return statistics.stdev(self._data)
109
Carl Meyerd658dea2018-08-28 01:11:56 -0600110 .. versionadded:: 3.8
111
Carl Meyerd658dea2018-08-28 01:11:56 -0600112
Éric Araujob10089e2010-11-18 14:22:08 +0000113.. function:: cmp_to_key(func)
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000114
Raymond Hettinger86e9b6b2014-11-09 17:20:56 -0800115 Transform an old-style comparison function to a :term:`key function`. Used
116 with tools that accept key functions (such as :func:`sorted`, :func:`min`,
Benjamin Petersoncca65312010-08-09 02:13:10 +0000117 :func:`max`, :func:`heapq.nlargest`, :func:`heapq.nsmallest`,
118 :func:`itertools.groupby`). This function is primarily used as a transition
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200119 tool for programs being converted from Python 2 which supported the use of
Benjamin Petersoncca65312010-08-09 02:13:10 +0000120 comparison functions.
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000121
Georg Brandl6c89a792012-01-25 22:36:25 +0100122 A comparison function is any callable that accept two arguments, compares them,
Benjamin Petersoncca65312010-08-09 02:13:10 +0000123 and returns a negative number for less-than, zero for equality, or a positive
124 number for greater-than. A key function is a callable that accepts one
Raymond Hettinger86e9b6b2014-11-09 17:20:56 -0800125 argument and returns another value to be used as the sort key.
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000126
Benjamin Petersoncca65312010-08-09 02:13:10 +0000127 Example::
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000128
Benjamin Petersoncca65312010-08-09 02:13:10 +0000129 sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000130
Raymond Hettinger86e9b6b2014-11-09 17:20:56 -0800131 For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`.
132
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000133 .. versionadded:: 3.2
134
Georg Brandl67b21b72010-08-17 15:07:14 +0000135
Raymond Hettingerb8218682019-05-26 11:27:35 -0700136.. decorator:: lru_cache(user_function)
137 lru_cache(maxsize=128, typed=False)
Georg Brandl2e7346a2010-07-31 18:09:23 +0000138
139 Decorator to wrap a function with a memoizing callable that saves up to the
140 *maxsize* most recent calls. It can save time when an expensive or I/O bound
141 function is periodically called with the same arguments.
142
Raymond Hettinger7496b412010-11-30 19:15:45 +0000143 Since a dictionary is used to cache results, the positional and keyword
144 arguments to the function must be hashable.
Georg Brandl2e7346a2010-07-31 18:09:23 +0000145
Raymond Hettinger902bcd92018-09-14 00:53:20 -0700146 Distinct argument patterns may be considered to be distinct calls with
147 separate cache entries. For example, `f(a=1, b=2)` and `f(b=2, a=1)`
148 differ in their keyword argument order and may have two separate cache
149 entries.
150
Raymond Hettingerb8218682019-05-26 11:27:35 -0700151 If *user_function* is specified, it must be a callable. This allows the
152 *lru_cache* decorator to be applied directly to a user function, leaving
153 the *maxsize* at its default value of 128::
154
155 @lru_cache
156 def count_vowels(sentence):
157 sentence = sentence.casefold()
158 return sum(sentence.count(vowel) for vowel in 'aeiou')
159
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300160 If *maxsize* is set to ``None``, the LRU feature is disabled and the cache can
Raymond Hettingerad9eaea2020-05-03 16:45:13 -0700161 grow without bound.
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000162
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300163 If *typed* is set to true, function arguments of different types will be
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -0700164 cached separately. For example, ``f(3)`` and ``f(3.0)`` will be treated
165 as distinct calls with distinct results.
166
Manjusaka051ff522019-11-12 15:30:18 +0800167 The wrapped function is instrumented with a :func:`cache_parameters`
168 function that returns a new :class:`dict` showing the values for *maxsize*
169 and *typed*. This is for information purposes only. Mutating the values
170 has no effect.
171
Raymond Hettinger7496b412010-11-30 19:15:45 +0000172 To help measure the effectiveness of the cache and tune the *maxsize*
173 parameter, the wrapped function is instrumented with a :func:`cache_info`
174 function that returns a :term:`named tuple` showing *hits*, *misses*,
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000175 *maxsize* and *currsize*. In a multi-threaded environment, the hits
176 and misses are approximate.
Nick Coghlan234515a2010-11-30 06:19:46 +0000177
Raymond Hettinger7496b412010-11-30 19:15:45 +0000178 The decorator also provides a :func:`cache_clear` function for clearing or
179 invalidating the cache.
Georg Brandl2e7346a2010-07-31 18:09:23 +0000180
Raymond Hettinger3fccfcb2010-08-17 19:19:29 +0000181 The original underlying function is accessible through the
Raymond Hettinger7496b412010-11-30 19:15:45 +0000182 :attr:`__wrapped__` attribute. This is useful for introspection, for
183 bypassing the cache, or for rewrapping the function with a different cache.
Nick Coghlan98876832010-08-17 06:17:18 +0000184
Raymond Hettingercc038582010-11-30 20:02:57 +0000185 An `LRU (least recently used) cache
Allen Guo3d542112020-05-12 18:54:18 -0400186 <https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)>`_
187 works best when the most recent calls are the best predictors of upcoming
188 calls (for example, the most popular articles on a news server tend to
189 change each day). The cache's size limit assures that the cache does not
190 grow without bound on long-running processes such as web servers.
Raymond Hettinger7496b412010-11-30 19:15:45 +0000191
Raymond Hettingerf0e0f202018-11-25 16:24:52 -0800192 In general, the LRU cache should only be used when you want to reuse
193 previously computed values. Accordingly, it doesn't make sense to cache
194 functions with side-effects, functions that need to create distinct mutable
195 objects on each call, or impure functions such as time() or random().
196
Raymond Hettingercc038582010-11-30 20:02:57 +0000197 Example of an LRU cache for static web content::
Raymond Hettinger7496b412010-11-30 19:15:45 +0000198
Raymond Hettinger17328e42013-04-06 20:27:33 -0700199 @lru_cache(maxsize=32)
Raymond Hettinger7496b412010-11-30 19:15:45 +0000200 def get_pep(num):
201 'Retrieve text of a Python Enhancement Proposal'
202 resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
203 try:
204 with urllib.request.urlopen(resource) as s:
205 return s.read()
206 except urllib.error.HTTPError:
207 return 'Not Found'
208
209 >>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
210 ... pep = get_pep(n)
211 ... print(n, len(pep))
212
Raymond Hettinger17328e42013-04-06 20:27:33 -0700213 >>> get_pep.cache_info()
214 CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
Georg Brandl2e7346a2010-07-31 18:09:23 +0000215
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000216 Example of efficiently computing
Georg Brandl5d941342016-02-26 19:37:12 +0100217 `Fibonacci numbers <https://en.wikipedia.org/wiki/Fibonacci_number>`_
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000218 using a cache to implement a
Georg Brandl5d941342016-02-26 19:37:12 +0100219 `dynamic programming <https://en.wikipedia.org/wiki/Dynamic_programming>`_
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000220 technique::
221
222 @lru_cache(maxsize=None)
223 def fib(n):
224 if n < 2:
225 return n
226 return fib(n-1) + fib(n-2)
227
Raymond Hettinger17328e42013-04-06 20:27:33 -0700228 >>> [fib(n) for n in range(16)]
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000229 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
230
Raymond Hettinger17328e42013-04-06 20:27:33 -0700231 >>> fib.cache_info()
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000232 CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
233
Georg Brandl2e7346a2010-07-31 18:09:23 +0000234 .. versionadded:: 3.2
235
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -0700236 .. versionchanged:: 3.3
237 Added the *typed* option.
238
Raymond Hettingerb8218682019-05-26 11:27:35 -0700239 .. versionchanged:: 3.8
240 Added the *user_function* option.
241
Manjusaka051ff522019-11-12 15:30:18 +0800242 .. versionadded:: 3.9
243 Added the function :func:`cache_parameters`
244
Georg Brandl8a1caa22010-07-29 16:01:11 +0000245.. decorator:: total_ordering
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000246
247 Given a class defining one or more rich comparison ordering methods, this
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000248 class decorator supplies the rest. This simplifies the effort involved
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000249 in specifying all of the possible rich comparison operations:
250
251 The class must define one of :meth:`__lt__`, :meth:`__le__`,
252 :meth:`__gt__`, or :meth:`__ge__`.
253 In addition, the class should supply an :meth:`__eq__` method.
254
255 For example::
256
257 @total_ordering
258 class Student:
Nick Coghlanf05d9812013-10-02 00:02:03 +1000259 def _is_valid_operand(self, other):
260 return (hasattr(other, "lastname") and
261 hasattr(other, "firstname"))
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000262 def __eq__(self, other):
Nick Coghlanf05d9812013-10-02 00:02:03 +1000263 if not self._is_valid_operand(other):
264 return NotImplemented
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000265 return ((self.lastname.lower(), self.firstname.lower()) ==
266 (other.lastname.lower(), other.firstname.lower()))
267 def __lt__(self, other):
Nick Coghlanf05d9812013-10-02 00:02:03 +1000268 if not self._is_valid_operand(other):
269 return NotImplemented
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000270 return ((self.lastname.lower(), self.firstname.lower()) <
271 (other.lastname.lower(), other.firstname.lower()))
272
Nick Coghlanf05d9812013-10-02 00:02:03 +1000273 .. note::
274
275 While this decorator makes it easy to create well behaved totally
276 ordered types, it *does* come at the cost of slower execution and
277 more complex stack traces for the derived comparison methods. If
278 performance benchmarking indicates this is a bottleneck for a given
279 application, implementing all six rich comparison methods instead is
280 likely to provide an easy speed boost.
281
Ben Avrahamibef7d292020-10-06 20:40:50 +0300282 .. note::
283
284 This decorator makes no attempt to override methods that have been
285 declared in the class *or its superclasses*. Meaning that if a
286 superclass defines a comparison operator, *total_ordering* will not
287 implement it again, even if the original method is abstract.
288
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000289 .. versionadded:: 3.2
290
Nick Coghlanf05d9812013-10-02 00:02:03 +1000291 .. versionchanged:: 3.4
292 Returning NotImplemented from the underlying comparison function for
293 unrecognised types is now supported.
Georg Brandl67b21b72010-08-17 15:07:14 +0000294
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300295.. function:: partial(func, /, *args, **keywords)
Georg Brandl116aa622007-08-15 14:28:22 +0000296
Andrei Petre83a07652018-10-22 23:11:20 -0700297 Return a new :ref:`partial object<partial-objects>` which when called
298 will behave like *func* called with the positional arguments *args*
299 and keyword arguments *keywords*. If more arguments are supplied to the
300 call, they are appended to *args*. If additional keyword arguments are
301 supplied, they extend and override *keywords*.
Georg Brandl116aa622007-08-15 14:28:22 +0000302 Roughly equivalent to::
303
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300304 def partial(func, /, *args, **keywords):
Georg Brandl116aa622007-08-15 14:28:22 +0000305 def newfunc(*fargs, **fkeywords):
Sergey Fedoseevb981fec2018-10-20 02:42:07 +0500306 newkeywords = {**keywords, **fkeywords}
Martin Panter0c0da482016-06-12 01:46:50 +0000307 return func(*args, *fargs, **newkeywords)
Georg Brandl116aa622007-08-15 14:28:22 +0000308 newfunc.func = func
309 newfunc.args = args
310 newfunc.keywords = keywords
311 return newfunc
312
313 The :func:`partial` is used for partial function application which "freezes"
314 some portion of a function's arguments and/or keywords resulting in a new object
315 with a simplified signature. For example, :func:`partial` can be used to create
316 a callable that behaves like the :func:`int` function where the *base* argument
Christian Heimesfe337bf2008-03-23 21:54:12 +0000317 defaults to two:
Georg Brandl116aa622007-08-15 14:28:22 +0000318
Christian Heimesfe337bf2008-03-23 21:54:12 +0000319 >>> from functools import partial
Georg Brandl116aa622007-08-15 14:28:22 +0000320 >>> basetwo = partial(int, base=2)
321 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
322 >>> basetwo('10010')
323 18
324
325
Serhiy Storchaka70c5f2a2019-06-01 11:38:24 +0300326.. class:: partialmethod(func, /, *args, **keywords)
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000327
328 Return a new :class:`partialmethod` descriptor which behaves
329 like :class:`partial` except that it is designed to be used as a method
330 definition rather than being directly callable.
331
332 *func* must be a :term:`descriptor` or a callable (objects which are both,
333 like normal functions, are handled as descriptors).
334
335 When *func* is a descriptor (such as a normal Python function,
336 :func:`classmethod`, :func:`staticmethod`, :func:`abstractmethod` or
337 another instance of :class:`partialmethod`), calls to ``__get__`` are
338 delegated to the underlying descriptor, and an appropriate
Andrei Petre83a07652018-10-22 23:11:20 -0700339 :ref:`partial object<partial-objects>` returned as the result.
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000340
341 When *func* is a non-descriptor callable, an appropriate bound method is
342 created dynamically. This behaves like a normal Python function when
343 used as a method: the *self* argument will be inserted as the first
344 positional argument, even before the *args* and *keywords* supplied to
345 the :class:`partialmethod` constructor.
346
347 Example::
348
Serhiy Storchakae042a452019-06-10 13:35:52 +0300349 >>> class Cell:
Benjamin Peterson3a434032014-03-30 15:07:09 -0400350 ... def __init__(self):
351 ... self._alive = False
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000352 ... @property
353 ... def alive(self):
354 ... return self._alive
355 ... def set_state(self, state):
356 ... self._alive = bool(state)
Nick Coghlan3daaf5f2013-11-04 23:32:16 +1000357 ... set_alive = partialmethod(set_state, True)
358 ... set_dead = partialmethod(set_state, False)
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000359 ...
360 >>> c = Cell()
361 >>> c.alive
362 False
363 >>> c.set_alive()
364 >>> c.alive
365 True
366
367 .. versionadded:: 3.4
368
369
Georg Brandl58f9e4f2008-04-19 22:18:33 +0000370.. function:: reduce(function, iterable[, initializer])
Georg Brandl116aa622007-08-15 14:28:22 +0000371
Brendan Jurd9df10022018-10-01 16:52:10 +1000372 Apply *function* of two arguments cumulatively to the items of *iterable*, from
373 left to right, so as to reduce the iterable to a single value. For example,
Georg Brandl116aa622007-08-15 14:28:22 +0000374 ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``.
375 The left argument, *x*, is the accumulated value and the right argument, *y*, is
Brendan Jurd9df10022018-10-01 16:52:10 +1000376 the update value from the *iterable*. If the optional *initializer* is present,
377 it is placed before the items of the iterable in the calculation, and serves as
378 a default when the iterable is empty. If *initializer* is not given and
379 *iterable* contains only one item, the first item is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000380
Raymond Hettinger558dcf32014-12-16 18:16:57 -0800381 Roughly equivalent to::
Raymond Hettinger64801682013-10-12 16:04:17 -0700382
383 def reduce(function, iterable, initializer=None):
384 it = iter(iterable)
385 if initializer is None:
386 value = next(it)
387 else:
388 value = initializer
389 for element in it:
390 value = function(value, element)
391 return value
392
Gerrit Hollbd81cbd2018-07-04 23:26:32 +0100393 See :func:`itertools.accumulate` for an iterator that yields all intermediate
394 values.
Georg Brandl116aa622007-08-15 14:28:22 +0000395
Daisuke Miyakawa0e61e672017-10-12 23:39:43 +0900396.. decorator:: singledispatch
Łukasz Langa6f692512013-06-05 12:20:24 +0200397
Daisuke Miyakawa0e61e672017-10-12 23:39:43 +0900398 Transform a function into a :term:`single-dispatch <single
Łukasz Langafdcf2b72013-06-07 22:54:03 +0200399 dispatch>` :term:`generic function`.
Łukasz Langa6f692512013-06-05 12:20:24 +0200400
401 To define a generic function, decorate it with the ``@singledispatch``
402 decorator. Note that the dispatch happens on the type of the first argument,
403 create your function accordingly::
404
405 >>> from functools import singledispatch
406 >>> @singledispatch
407 ... def fun(arg, verbose=False):
408 ... if verbose:
409 ... print("Let me just say,", end=" ")
410 ... print(arg)
411
412 To add overloaded implementations to the function, use the :func:`register`
Łukasz Langae5697532017-12-11 13:56:31 -0800413 attribute of the generic function. It is a decorator. For functions
414 annotated with types, the decorator will infer the type of the first
415 argument automatically::
Łukasz Langa6f692512013-06-05 12:20:24 +0200416
Łukasz Langae5697532017-12-11 13:56:31 -0800417 >>> @fun.register
418 ... def _(arg: int, verbose=False):
Łukasz Langa6f692512013-06-05 12:20:24 +0200419 ... if verbose:
420 ... print("Strength in numbers, eh?", end=" ")
421 ... print(arg)
422 ...
Łukasz Langae5697532017-12-11 13:56:31 -0800423 >>> @fun.register
424 ... def _(arg: list, verbose=False):
Łukasz Langa6f692512013-06-05 12:20:24 +0200425 ... if verbose:
426 ... print("Enumerate this:")
427 ... for i, elem in enumerate(arg):
428 ... print(i, elem)
429
Łukasz Langae5697532017-12-11 13:56:31 -0800430 For code which doesn't use type annotations, the appropriate type
431 argument can be passed explicitly to the decorator itself::
432
433 >>> @fun.register(complex)
434 ... def _(arg, verbose=False):
435 ... if verbose:
436 ... print("Better than complicated.", end=" ")
437 ... print(arg.real, arg.imag)
438 ...
439
440
Łukasz Langa6f692512013-06-05 12:20:24 +0200441 To enable registering lambdas and pre-existing functions, the
442 :func:`register` attribute can be used in a functional form::
443
444 >>> def nothing(arg, verbose=False):
445 ... print("Nothing.")
446 ...
447 >>> fun.register(type(None), nothing)
448
449 The :func:`register` attribute returns the undecorated function which
450 enables decorator stacking, pickling, as well as creating unit tests for
451 each variant independently::
452
453 >>> @fun.register(float)
454 ... @fun.register(Decimal)
455 ... def fun_num(arg, verbose=False):
456 ... if verbose:
457 ... print("Half of your number:", end=" ")
458 ... print(arg / 2)
459 ...
460 >>> fun_num is fun
461 False
462
463 When called, the generic function dispatches on the type of the first
464 argument::
465
466 >>> fun("Hello, world.")
467 Hello, world.
468 >>> fun("test.", verbose=True)
469 Let me just say, test.
470 >>> fun(42, verbose=True)
471 Strength in numbers, eh? 42
472 >>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)
473 Enumerate this:
474 0 spam
475 1 spam
476 2 eggs
477 3 spam
478 >>> fun(None)
479 Nothing.
480 >>> fun(1.23)
481 0.615
482
483 Where there is no registered implementation for a specific type, its
484 method resolution order is used to find a more generic implementation.
485 The original function decorated with ``@singledispatch`` is registered
486 for the base ``object`` type, which means it is used if no better
487 implementation is found.
488
Batuhan Taşkaya24555ce2019-11-19 11:16:46 +0300489 If an implementation registered to :term:`abstract base class`, virtual
490 subclasses will be dispatched to that implementation::
491
492 >>> from collections.abc import Mapping
493 >>> @fun.register
494 ... def _(arg: Mapping, verbose=False):
495 ... if verbose:
496 ... print("Keys & Values")
497 ... for key, value in arg.items():
498 ... print(key, "=>", value)
499 ...
500 >>> fun({"a": "b"})
501 a => b
502
Łukasz Langa6f692512013-06-05 12:20:24 +0200503 To check which implementation will the generic function choose for
504 a given type, use the ``dispatch()`` attribute::
505
506 >>> fun.dispatch(float)
507 <function fun_num at 0x1035a2840>
508 >>> fun.dispatch(dict) # note: default implementation
509 <function fun at 0x103fe0000>
510
511 To access all registered implementations, use the read-only ``registry``
512 attribute::
513
514 >>> fun.registry.keys()
515 dict_keys([<class 'NoneType'>, <class 'int'>, <class 'object'>,
516 <class 'decimal.Decimal'>, <class 'list'>,
517 <class 'float'>])
518 >>> fun.registry[float]
519 <function fun_num at 0x1035a2840>
520 >>> fun.registry[object]
521 <function fun at 0x103fe0000>
522
523 .. versionadded:: 3.4
524
Łukasz Langae5697532017-12-11 13:56:31 -0800525 .. versionchanged:: 3.7
526 The :func:`register` attribute supports using type annotations.
527
Łukasz Langa6f692512013-06-05 12:20:24 +0200528
Ethan Smithc6512752018-05-26 16:38:33 -0400529.. class:: singledispatchmethod(func)
530
531 Transform a method into a :term:`single-dispatch <single
532 dispatch>` :term:`generic function`.
533
534 To define a generic method, decorate it with the ``@singledispatchmethod``
535 decorator. Note that the dispatch happens on the type of the first non-self
536 or non-cls argument, create your function accordingly::
537
538 class Negator:
539 @singledispatchmethod
540 def neg(self, arg):
541 raise NotImplementedError("Cannot negate a")
542
543 @neg.register
544 def _(self, arg: int):
545 return -arg
546
547 @neg.register
548 def _(self, arg: bool):
549 return not arg
550
551 ``@singledispatchmethod`` supports nesting with other decorators such as
552 ``@classmethod``. Note that to allow for ``dispatcher.register``,
553 ``singledispatchmethod`` must be the *outer most* decorator. Here is the
554 ``Negator`` class with the ``neg`` methods being class bound::
555
556 class Negator:
557 @singledispatchmethod
558 @classmethod
559 def neg(cls, arg):
560 raise NotImplementedError("Cannot negate a")
561
562 @neg.register
563 @classmethod
564 def _(cls, arg: int):
565 return -arg
566
567 @neg.register
568 @classmethod
569 def _(cls, arg: bool):
570 return not arg
571
572 The same pattern can be used for other similar decorators: ``staticmethod``,
573 ``abstractmethod``, and others.
574
Inada Naokibc284f02019-03-27 18:15:17 +0900575 .. versionadded:: 3.8
576
577
Georg Brandl036490d2009-05-17 13:00:36 +0000578.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000579
580 Update a *wrapper* function to look like the *wrapped* function. The optional
581 arguments are tuples to specify which attributes of the original function are
582 assigned directly to the matching attributes on the wrapper function and which
583 attributes of the wrapper function are updated with the corresponding attributes
584 from the original function. The default values for these arguments are the
Berker Peksag472233e2016-04-18 21:20:50 +0300585 module level constants ``WRAPPER_ASSIGNMENTS`` (which assigns to the wrapper
586 function's ``__module__``, ``__name__``, ``__qualname__``, ``__annotations__``
587 and ``__doc__``, the documentation string) and ``WRAPPER_UPDATES`` (which
588 updates the wrapper function's ``__dict__``, i.e. the instance dictionary).
Georg Brandl116aa622007-08-15 14:28:22 +0000589
Nick Coghlan98876832010-08-17 06:17:18 +0000590 To allow access to the original function for introspection and other purposes
591 (e.g. bypassing a caching decorator such as :func:`lru_cache`), this function
Nick Coghlan24c05bc2013-07-15 21:13:08 +1000592 automatically adds a ``__wrapped__`` attribute to the wrapper that refers to
593 the function being wrapped.
Nick Coghlan98876832010-08-17 06:17:18 +0000594
Christian Heimesd8654cf2007-12-02 15:22:16 +0000595 The main intended use for this function is in :term:`decorator` functions which
596 wrap the decorated function and return the wrapper. If the wrapper function is
597 not updated, the metadata of the returned function will reflect the wrapper
Georg Brandl116aa622007-08-15 14:28:22 +0000598 definition rather than the original function definition, which is typically less
599 than helpful.
600
Nick Coghlan98876832010-08-17 06:17:18 +0000601 :func:`update_wrapper` may be used with callables other than functions. Any
602 attributes named in *assigned* or *updated* that are missing from the object
603 being wrapped are ignored (i.e. this function will not attempt to set them
604 on the wrapper function). :exc:`AttributeError` is still raised if the
605 wrapper function itself is missing any attributes named in *updated*.
606
607 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000608 Automatic addition of the ``__wrapped__`` attribute.
Nick Coghlan98876832010-08-17 06:17:18 +0000609
610 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000611 Copying of the ``__annotations__`` attribute by default.
Nick Coghlan98876832010-08-17 06:17:18 +0000612
613 .. versionchanged:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000614 Missing attributes no longer trigger an :exc:`AttributeError`.
615
Nick Coghlan24c05bc2013-07-15 21:13:08 +1000616 .. versionchanged:: 3.4
617 The ``__wrapped__`` attribute now always refers to the wrapped
618 function, even if that function defined a ``__wrapped__`` attribute.
619 (see :issue:`17482`)
620
Georg Brandl116aa622007-08-15 14:28:22 +0000621
Georg Brandl8a1caa22010-07-29 16:01:11 +0000622.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000623
Ezio Melotti67f6d5f2014-08-05 08:14:28 +0300624 This is a convenience function for invoking :func:`update_wrapper` as a
625 function decorator when defining a wrapper function. It is equivalent to
626 ``partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)``.
627 For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000628
Christian Heimesfe337bf2008-03-23 21:54:12 +0000629 >>> from functools import wraps
Georg Brandl116aa622007-08-15 14:28:22 +0000630 >>> def my_decorator(f):
631 ... @wraps(f)
632 ... def wrapper(*args, **kwds):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000633 ... print('Calling decorated function')
Georg Brandl116aa622007-08-15 14:28:22 +0000634 ... return f(*args, **kwds)
635 ... return wrapper
636 ...
637 >>> @my_decorator
638 ... def example():
639 ... """Docstring"""
Georg Brandl6911e3c2007-09-04 07:15:32 +0000640 ... print('Called example function')
Georg Brandl116aa622007-08-15 14:28:22 +0000641 ...
642 >>> example()
643 Calling decorated function
644 Called example function
645 >>> example.__name__
646 'example'
647 >>> example.__doc__
648 'Docstring'
649
650 Without the use of this decorator factory, the name of the example function
651 would have been ``'wrapper'``, and the docstring of the original :func:`example`
652 would have been lost.
653
654
655.. _partial-objects:
656
657:class:`partial` Objects
658------------------------
659
660:class:`partial` objects are callable objects created by :func:`partial`. They
661have three read-only attributes:
662
663
664.. attribute:: partial.func
665
666 A callable object or function. Calls to the :class:`partial` object will be
667 forwarded to :attr:`func` with new arguments and keywords.
668
669
670.. attribute:: partial.args
671
672 The leftmost positional arguments that will be prepended to the positional
673 arguments provided to a :class:`partial` object call.
674
675
676.. attribute:: partial.keywords
677
678 The keyword arguments that will be supplied when the :class:`partial` object is
679 called.
680
681:class:`partial` objects are like :class:`function` objects in that they are
682callable, weak referencable, and can have attributes. There are some important
Martin Panterbae5d812016-06-18 03:57:31 +0000683differences. For instance, the :attr:`~definition.__name__` and :attr:`__doc__` attributes
Georg Brandl116aa622007-08-15 14:28:22 +0000684are not created automatically. Also, :class:`partial` objects defined in
685classes behave like static methods and do not transform into bound methods
Raymond Hettinger48be6b12020-10-24 18:17:17 -0700686during instance attribute look-up.