Debian Codegraph @

Doc/library/functools.rst

raw
1 :mod:`!functools` --- Higher-order functions and operations on callable objects
2 ===============================================================================
3
4 .. module:: functools
5 :synopsis: Higher-order functions and operations on callable objects.
6
7 .. moduleauthor:: Peter Harris <[email protected]>
8 .. moduleauthor:: Raymond Hettinger <[email protected]>
9 .. moduleauthor:: Nick Coghlan <[email protected]>
10 .. moduleauthor:: Ɓukasz Langa <[email protected]>
11 .. moduleauthor:: Pablo Galindo <[email protected]>
12 .. sectionauthor:: Peter Harris <[email protected]>
13
14 **Source code:** :source:`Lib/functools.py`
15
16 .. testsetup:: default
17
18 import functools
19 from functools import *
20
21 --------------
22
23 The :mod:`functools` module is for higher-order functions: functions that act on
24 or return other functions. In general, any callable object can be treated as a
25 function for the purposes of this module.
26
27 The :mod:`functools` module defines the following functions:
28
29 .. 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 :deco:`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) # no new calls, just returns the cached result
48 120
49 >>> factorial(12) # two new recursive calls, factorial(10) is cached
50 479001600
51
52 The cache is threadsafe so that the wrapped function can be used in
53 multiple threads. This means that the underlying data structure will
54 remain coherent during concurrent updates.
55
56 It is possible for the wrapped function to be called more than once if
57 another thread makes an additional call before the initial call has been
58 completed and cached.
59
60 .. versionadded:: 3.9
61
62
63 .. decorator:: cached_property(func)
64
65 Transform a method of a class into a property whose value is computed once
66 and then cached as a normal attribute for the life of the instance. Similar
67 to :deco:`property`, with the addition of caching. Useful for expensive
68 computed properties of instances that are otherwise effectively immutable.
69
70 Example::
71
72 class DataSet:
73
74 def __init__(self, sequence_of_numbers):
75 self._data = tuple(sequence_of_numbers)
76
77 @cached_property
78 def stdev(self):
79 return statistics.stdev(self._data)
80
81 The mechanics of :deco:`cached_property` are somewhat different from
82 :deco:`property`. A regular property blocks attribute writes unless a
83 setter is defined. In contrast, a *cached_property* allows writes.
84
85 The *cached_property* decorator only runs on lookups and only when an
86 attribute of the same name doesn't exist. When it does run, the
87 *cached_property* writes to the attribute with the same name. Subsequent
88 attribute reads and writes take precedence over the *cached_property*
89 method and it works like a normal attribute.
90
91 The cached value can be cleared by deleting the attribute. This
92 allows the *cached_property* method to run again.
93
94 The *cached_property* does not prevent a possible race condition in
95 multi-threaded usage. The getter function could run more than once on the
96 same instance, with the latest run setting the cached value. If the cached
97 property is idempotent or otherwise not harmful to run more than once on an
98 instance, this is fine. If synchronization is needed, implement the necessary
99 locking inside the decorated getter function or around the cached property
100 access.
101
102 Note, this decorator interferes with the operation of :pep:`412`
103 key-sharing dictionaries. This means that instance dictionaries
104 can take more space than usual.
105
106 Also, this decorator requires that the ``__dict__`` attribute on each instance
107 be a mutable mapping. This means it will not work with some types, such as
108 metaclasses (since the ``__dict__`` attributes on type instances are
109 read-only proxies for the class namespace), and those that specify
110 ``__slots__`` without including ``__dict__`` as one of the defined slots
111 (as such classes don't provide a ``__dict__`` attribute at all).
112
113 If a mutable mapping is not available or if space-efficient key sharing is
114 desired, an effect similar to :deco:`cached_property` can also be achieved by
115 stacking :deco:`property` on top of :deco:`lru_cache`. See
116 :ref:`faq-cache-method-calls` for more details on how this differs from :deco:`cached_property`.
117
118 .. versionadded:: 3.8
119
120 .. versionchanged:: 3.12
121 Prior to Python 3.12, :deco:`!cached_property` included an undocumented lock to
122 ensure that in multi-threaded usage the getter function was guaranteed to
123 run only once per instance. However, the lock was per-property, not
124 per-instance, which could result in unacceptably high lock contention. In
125 Python 3.12+ this locking is removed.
126
127
128 .. function:: cmp_to_key(func)
129
130 Transform an old-style comparison function to a :term:`key function`. Used
131 with tools that accept key functions (such as :func:`sorted`, :func:`min`,
132 :func:`max`, :func:`heapq.nlargest`, :func:`heapq.nsmallest`,
133 :func:`itertools.groupby`). This function is primarily used as a transition
134 tool for programs being converted from Python 2 which supported the use of
135 comparison functions.
136
137 A comparison function is any callable that accepts two arguments, compares them,
138 and returns a negative number for less-than, zero for equality, or a positive
139 number for greater-than. A key function is a callable that accepts one
140 argument and returns another value to be used as the sort key.
141
142 Example::
143
144 sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order
145
146 For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`.
147
148 .. versionadded:: 3.2
149
150
151 .. decorator:: lru_cache(user_function)
152 lru_cache(maxsize=128, typed=False)
153
154 Decorator to wrap a function with a memoizing callable that saves up to the
155 *maxsize* most recent calls. It can save time when an expensive or I/O bound
156 function is periodically called with the same arguments.
157
158 The cache is threadsafe so that the wrapped function can be used in
159 multiple threads. This means that the underlying data structure will
160 remain coherent during concurrent updates.
161
162 It is possible for the wrapped function to be called more than once if
163 another thread makes an additional call before the initial call has been
164 completed and cached.
165
166 Since a dictionary is used to cache results, the positional and keyword
167 arguments to the function must be :term:`hashable`.
168
169 Distinct argument patterns may be considered to be distinct calls with
170 separate cache entries. For example, ``f(a=1, b=2)`` and ``f(b=2, a=1)``
171 differ in their keyword argument order and may have two separate cache
172 entries.
173
174 If *user_function* is specified, it must be a callable. This allows the
175 *lru_cache* decorator to be applied directly to a user function, leaving
176 the *maxsize* at its default value of 128::
177
178 @lru_cache
179 def count_vowels(sentence):
180 return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
181
182 If *maxsize* is set to ``None``, the LRU feature is disabled and the cache can
183 grow without bound.
184
185 If *typed* is set to true, function arguments of different types will be
186 cached separately. If *typed* is false, the implementation will usually
187 regard them as equivalent calls and only cache a single result. (Some
188 types such as *str* and *int* may be cached separately even when *typed*
189 is false.)
190
191 Note, type specificity applies only to the function's immediate arguments
192 rather than their contents. The scalar arguments, ``Decimal(42)`` and
193 ``Fraction(42)`` are treated as distinct calls with distinct results.
194 In contrast, the tuple arguments ``('answer', Decimal(42))`` and
195 ``('answer', Fraction(42))`` are treated as equivalent.
196
197 The wrapped function is instrumented with a :func:`!cache_parameters`
198 function that returns a new :class:`dict` showing the values for *maxsize*
199 and *typed*. This is for information purposes only. Mutating the values
200 has no effect.
201
202 .. method:: lru_cache.cache_info()
203 :no-typesetting:
204
205 To help measure the effectiveness of the cache and tune the *maxsize*
206 parameter, the wrapped function is instrumented with a :func:`!cache_info`
207 function that returns a :term:`named tuple` showing *hits*, *misses*,
208 *maxsize* and *currsize*.
209
210 .. method:: lru_cache.cache_clear()
211 :no-typesetting:
212
213 The decorator also provides a :func:`!cache_clear` function for clearing or
214 invalidating the cache.
215
216 The original underlying function is accessible through the
217 :attr:`__wrapped__` attribute. This is useful for introspection, for
218 bypassing the cache, or for rewrapping the function with a different cache.
219
220 The cache keeps references to the arguments and return values until they age
221 out of the cache or until the cache is cleared.
222
223 If a method is cached, the ``self`` instance argument is included in the
224 cache. See :ref:`faq-cache-method-calls`
225
226 An `LRU (least recently used) cache
227 <https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_Recently_Used_(LRU)>`_
228 works best when the most recent calls are the best predictors of upcoming
229 calls (for example, the most popular articles on a news server tend to
230 change each day). The cache's size limit assures that the cache does not
231 grow without bound on long-running processes such as web servers.
232
233 In general, the LRU cache should only be used when you want to reuse
234 previously computed values. Accordingly, it doesn't make sense to cache
235 functions with side-effects, functions that need to create
236 distinct mutable objects on each call (such as generators and async functions),
237 or impure functions such as time() or random().
238
239 Example of an LRU cache for static web content::
240
241 @lru_cache(maxsize=32)
242 def get_pep(num):
243 'Retrieve text of a Python Enhancement Proposal'
244 resource = f'https://peps.python.org/pep-{num:04d}'
245 try:
246 with urllib.request.urlopen(resource) as s:
247 return s.read()
248 except urllib.error.HTTPError:
249 return 'Not Found'
250
251 >>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
252 ... pep = get_pep(n)
253 ... print(n, len(pep))
254
255 >>> get_pep.cache_info()
256 CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
257
258 Example of efficiently computing
259 `Fibonacci numbers <https://en.wikipedia.org/wiki/Fibonacci_number>`_
260 using a cache to implement a
261 `dynamic programming <https://en.wikipedia.org/wiki/Dynamic_programming>`_
262 technique::
263
264 @lru_cache(maxsize=None)
265 def fib(n):
266 if n < 2:
267 return n
268 return fib(n-1) + fib(n-2)
269
270 >>> [fib(n) for n in range(16)]
271 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
272
273 >>> fib.cache_info()
274 CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
275
276 .. versionadded:: 3.2
277
278 .. versionchanged:: 3.3
279 Added the *typed* option.
280
281 .. versionchanged:: 3.8
282 Added the *user_function* option.
283
284 .. versionchanged:: 3.9
285 Added the function :func:`!cache_parameters`
286
287 .. decorator:: total_ordering
288
289 Given a class defining one or more rich comparison ordering methods, this
290 class decorator supplies the rest. This simplifies the effort involved
291 in specifying all of the possible rich comparison operations:
292
293 The class must define one of :meth:`~object.__lt__`, :meth:`~object.__le__`,
294 :meth:`~object.__gt__`, or :meth:`~object.__ge__`.
295 In addition, the class should supply an :meth:`~object.__eq__` method.
296
297 For example::
298
299 @total_ordering
300 class Student:
301 def _is_valid_operand(self, other):
302 return (hasattr(other, "lastname") and
303 hasattr(other, "firstname"))
304 def __eq__(self, other):
305 if not self._is_valid_operand(other):
306 return NotImplemented
307 return ((self.lastname.lower(), self.firstname.lower()) ==
308 (other.lastname.lower(), other.firstname.lower()))
309 def __lt__(self, other):
310 if not self._is_valid_operand(other):
311 return NotImplemented
312 return ((self.lastname.lower(), self.firstname.lower()) <
313 (other.lastname.lower(), other.firstname.lower()))
314
315 .. note::
316
317 While this decorator makes it easy to create well behaved totally
318 ordered types, it *does* come at the cost of slower execution and
319 more complex stack traces for the derived comparison methods. If
320 performance benchmarking indicates this is a bottleneck for a given
321 application, implementing all six rich comparison methods instead is
322 likely to provide an easy speed boost.
323
324 .. note::
325
326 This decorator makes no attempt to override methods that have been
327 declared in the class *or its superclasses*. Meaning that if a
328 superclass defines a comparison operator, *total_ordering* will not
329 implement it again, even if the original method is abstract.
330
331 .. versionadded:: 3.2
332
333 .. versionchanged:: 3.4
334 Returning ``NotImplemented`` from the underlying comparison function for
335 unrecognised types is now supported.
336
337 .. function:: partial(func, /, *args, **keywords)
338
339 Return a new :ref:`partial object<partial-objects>` which when called
340 will behave like *func* called with the positional arguments *args*
341 and keyword arguments *keywords*. If more arguments are supplied to the
342 call, they are appended to *args*. If additional keyword arguments are
343 supplied, they extend and override *keywords*.
344 Roughly equivalent to::
345
346 def partial(func, /, *args, **keywords):
347 def newfunc(*fargs, **fkeywords):
348 newkeywords = {**keywords, **fkeywords}
349 return func(*args, *fargs, **newkeywords)
350 newfunc.func = func
351 newfunc.args = args
352 newfunc.keywords = keywords
353 return newfunc
354
355 The :func:`partial` is used for partial function application which "freezes"
356 some portion of a function's arguments and/or keywords resulting in a new object
357 with a simplified signature. For example, :func:`partial` can be used to create
358 a callable that behaves like the :func:`int` function where the *base* argument
359 defaults to two:
360
361 >>> from functools import partial
362 >>> basetwo = partial(int, base=2)
363 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
364 >>> basetwo('10010')
365 18
366
367
368 .. class:: partialmethod(func, /, *args, **keywords)
369
370 Return a new :class:`partialmethod` descriptor which behaves
371 like :class:`partial` except that it is designed to be used as a method
372 definition rather than being directly callable.
373
374 *func* must be a :term:`descriptor` or a callable (objects which are both,
375 like normal functions, are handled as descriptors).
376
377 When *func* is a descriptor (such as a normal Python function,
378 :func:`classmethod`, :func:`staticmethod`, :func:`~abc.abstractmethod` or
379 another instance of :class:`partialmethod`), calls to ``__get__`` are
380 delegated to the underlying descriptor, and an appropriate
381 :ref:`partial object<partial-objects>` returned as the result.
382
383 When *func* is a non-descriptor callable, an appropriate bound method is
384 created dynamically. This behaves like a normal Python function when
385 used as a method: the *self* argument will be inserted as the first
386 positional argument, even before the *args* and *keywords* supplied to
387 the :class:`partialmethod` constructor.
388
389 Example::
390
391 >>> class Cell:
392 ... def __init__(self):
393 ... self._alive = False
394 ... @property
395 ... def alive(self):
396 ... return self._alive
397 ... def set_state(self, state):
398 ... self._alive = bool(state)
399 ... set_alive = partialmethod(set_state, True)
400 ... set_dead = partialmethod(set_state, False)
401 ...
402 >>> c = Cell()
403 >>> c.alive
404 False
405 >>> c.set_alive()
406 >>> c.alive
407 True
408
409 .. versionadded:: 3.4
410
411
412 .. function:: reduce(function, iterable[, initial], /)
413
414 Apply *function* of two arguments cumulatively to the items of *iterable*, from
415 left to right, so as to reduce the iterable to a single value. For example,
416 ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``.
417 The left argument, *x*, is the accumulated value and the right argument, *y*, is
418 the update value from the *iterable*. If the optional *initial* is present,
419 it is placed before the items of the iterable in the calculation, and serves as
420 a default when the iterable is empty. If *initial* is not given and
421 *iterable* contains only one item, the first item is returned.
422
423 Roughly equivalent to::
424
425 initial_missing = object()
426
427 def reduce(function, iterable, initial=initial_missing, /):
428 it = iter(iterable)
429 if initial is initial_missing:
430 value = next(it)
431 else:
432 value = initial
433 for element in it:
434 value = function(value, element)
435 return value
436
437 See :func:`itertools.accumulate` for an iterator that yields all intermediate
438 values.
439
440 .. decorator:: singledispatch
441
442 Transform a function into a :term:`single-dispatch <single
443 dispatch>` :term:`generic function`.
444
445 To define a generic function, decorate it with the ``@singledispatch``
446 decorator. When defining a function using ``@singledispatch``, note that the
447 dispatch happens on the type of the first argument::
448
449 >>> from functools import singledispatch
450 >>> @singledispatch
451 ... def fun(arg, verbose=False):
452 ... if verbose:
453 ... print("Let me just say,", end=" ")
454 ... print(arg)
455
456 .. method:: singledispatch.register()
457 :no-typesetting:
458
459 To add overloaded implementations to the function, use the :func:`!register`
460 attribute of the generic function, which can be used as a decorator. For
461 functions annotated with types, the decorator will infer the type of the
462 first argument automatically::
463
464 >>> @fun.register
465 ... def _(arg: int, verbose=False):
466 ... if verbose:
467 ... print("Strength in numbers, eh?", end=" ")
468 ... print(arg)
469 ...
470 >>> @fun.register
471 ... def _(arg: list, verbose=False):
472 ... if verbose:
473 ... print("Enumerate this:")
474 ... for i, elem in enumerate(arg):
475 ... print(i, elem)
476
477 :data:`types.UnionType` and :data:`typing.Union` can also be used::
478
479 >>> @fun.register
480 ... def _(arg: int | float, verbose=False):
481 ... if verbose:
482 ... print("Strength in numbers, eh?", end=" ")
483 ... print(arg)
484 ...
485 >>> from typing import Union
486 >>> @fun.register
487 ... def _(arg: Union[list, set], verbose=False):
488 ... if verbose:
489 ... print("Enumerate this:")
490 ... for i, elem in enumerate(arg):
491 ... print(i, elem)
492 ...
493
494 For code which doesn't use type annotations, the appropriate type
495 argument can be passed explicitly to the decorator itself::
496
497 >>> @fun.register(complex)
498 ... def _(arg, verbose=False):
499 ... if verbose:
500 ... print("Better than complicated.", end=" ")
501 ... print(arg.real, arg.imag)
502 ...
503
504 For code that dispatches on a collections type (e.g., ``list``), but wants
505 to typehint the items of the collection (e.g., ``list[int]``), the
506 dispatch type should be passed explicitly to the decorator itself with the
507 typehint going into the function definition::
508
509 >>> @fun.register(list)
510 ... def _(arg: list[int], verbose=False):
511 ... if verbose:
512 ... print("Enumerate this:")
513 ... for i, elem in enumerate(arg):
514 ... print(i, elem)
515
516 .. note::
517
518 At runtime the function will dispatch on an instance of a list regardless
519 of the type contained within the list i.e. ``[1,2,3]`` will be
520 dispatched the same as ``["foo", "bar", "baz"]``. The annotation
521 provided in this example is for static type checkers only and has no
522 runtime impact.
523
524 To enable registering :term:`lambdas<lambda>` and pre-existing functions,
525 the :func:`~singledispatch.register` attribute can also be used in a functional form::
526
527 >>> def nothing(arg, verbose=False):
528 ... print("Nothing.")
529 ...
530 >>> fun.register(type(None), nothing)
531
532 The :func:`~singledispatch.register` attribute returns the undecorated function. This
533 enables decorator stacking, :mod:`pickling<pickle>`, and the creation
534 of unit tests for each variant independently::
535
536 >>> @fun.register(float)
537 ... @fun.register(Decimal)
538 ... def fun_num(arg, verbose=False):
539 ... if verbose:
540 ... print("Half of your number:", end=" ")
541 ... print(arg / 2)
542 ...
543 >>> fun_num is fun
544 False
545
546 When called, the generic function dispatches on the type of the first
547 argument::
548
549 >>> fun("Hello, world.")
550 Hello, world.
551 >>> fun("test.", verbose=True)
552 Let me just say, test.
553 >>> fun(42, verbose=True)
554 Strength in numbers, eh? 42
555 >>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)
556 Enumerate this:
557 0 spam
558 1 spam
559 2 eggs
560 3 spam
561 >>> fun(None)
562 Nothing.
563 >>> fun(1.23)
564 0.615
565
566 Where there is no registered implementation for a specific type, its
567 method resolution order is used to find a more generic implementation.
568 The original function decorated with ``@singledispatch`` is registered
569 for the base :class:`object` type, which means it is used if no better
570 implementation is found.
571
572 If an implementation is registered to an :term:`abstract base class`,
573 virtual subclasses of the base class will be dispatched to that
574 implementation::
575
576 >>> from collections.abc import Mapping
577 >>> @fun.register
578 ... def _(arg: Mapping, verbose=False):
579 ... if verbose:
580 ... print("Keys & Values")
581 ... for key, value in arg.items():
582 ... print(key, "=>", value)
583 ...
584 >>> fun({"a": "b"})
585 a => b
586
587 To check which implementation the generic function will choose for
588 a given type, use the ``dispatch()`` attribute::
589
590 >>> fun.dispatch(float)
591 <function fun_num at 0x1035a2840>
592 >>> fun.dispatch(dict) # note: default implementation
593 <function fun at 0x103fe0000>
594
595 To access all registered implementations, use the read-only ``registry``
596 attribute::
597
598 >>> fun.registry.keys()
599 dict_keys([<class 'NoneType'>, <class 'int'>, <class 'object'>,
600 <class 'decimal.Decimal'>, <class 'list'>,
601 <class 'float'>])
602 >>> fun.registry[float]
603 <function fun_num at 0x1035a2840>
604 >>> fun.registry[object]
605 <function fun at 0x103fe0000>
606
607 .. versionadded:: 3.4
608
609 .. versionchanged:: 3.7
610 The :func:`~singledispatch.register` attribute now supports using type annotations.
611
612 .. versionchanged:: 3.11
613 The :func:`~singledispatch.register` attribute now supports :data:`types.UnionType`
614 and :data:`typing.Union` as type annotations.
615
616
617 .. class:: singledispatchmethod(func)
618
619 Transform a method into a :term:`single-dispatch <single
620 dispatch>` :term:`generic function`.
621
622 To define a generic method, decorate it with the ``@singledispatchmethod``
623 decorator. When defining a method using ``@singledispatchmethod``, note
624 that the dispatch happens on the type of the first non-*self* or non-*cls*
625 argument::
626
627 class Negator:
628 @singledispatchmethod
629 def neg(self, arg):
630 raise NotImplementedError("Cannot negate a")
631
632 @neg.register
633 def _(self, arg: int):
634 return -arg
635
636 @neg.register
637 def _(self, arg: bool):
638 return not arg
639
640 ``@singledispatchmethod`` supports nesting with other decorators such as
641 :deco:`classmethod`. Note that to allow for
642 ``dispatcher.register``, ``singledispatchmethod`` must be the *outer most*
643 decorator. Here is the ``Negator`` class with the ``neg`` methods bound to
644 the class, rather than an instance of the class::
645
646 class Negator:
647 @singledispatchmethod
648 @classmethod
649 def neg(cls, arg):
650 raise NotImplementedError("Cannot negate a")
651
652 @neg.register
653 @classmethod
654 def _(cls, arg: int):
655 return -arg
656
657 @neg.register
658 @classmethod
659 def _(cls, arg: bool):
660 return not arg
661
662 The same pattern can be used for other similar decorators:
663 :deco:`staticmethod`, :deco:`~abc.abstractmethod`, and others.
664
665 .. versionadded:: 3.8
666
667
668 .. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
669
670 Update a *wrapper* function to look like the *wrapped* function. The optional
671 arguments are tuples to specify which attributes of the original function are
672 assigned directly to the matching attributes on the wrapper function and which
673 attributes of the wrapper function are updated with the corresponding attributes
674 from the original function. The default values for these arguments are the
675 module level constants ``WRAPPER_ASSIGNMENTS`` (which assigns to the wrapper
676 function's :attr:`~function.__module__`, :attr:`~function.__name__`,
677 :attr:`~function.__qualname__`, :attr:`~function.__annotations__`,
678 :attr:`~function.__type_params__`, and :attr:`~function.__doc__`, the
679 documentation string) and ``WRAPPER_UPDATES`` (which updates the wrapper
680 function's :attr:`~function.__dict__`, i.e. the instance dictionary).
681
682 To allow access to the original function for introspection and other purposes
683 (e.g. bypassing a caching decorator such as :deco:`lru_cache`), this function
684 automatically adds a ``__wrapped__`` attribute to the wrapper that refers to
685 the function being wrapped.
686
687 The main intended use for this function is in :term:`decorator` functions which
688 wrap the decorated function and return the wrapper. If the wrapper function is
689 not updated, the metadata of the returned function will reflect the wrapper
690 definition rather than the original function definition, which is typically less
691 than helpful.
692
693 :func:`update_wrapper` may be used with callables other than functions. Any
694 attributes named in *assigned* or *updated* that are missing from the object
695 being wrapped are ignored (i.e. this function will not attempt to set them
696 on the wrapper function). :exc:`AttributeError` is still raised if the
697 wrapper function itself is missing any attributes named in *updated*.
698
699 .. versionchanged:: 3.2
700 The ``__wrapped__`` attribute is now automatically added.
701 The :attr:`~function.__annotations__` attribute is now copied by default.
702 Missing attributes no longer trigger an :exc:`AttributeError`.
703
704 .. versionchanged:: 3.4
705 The ``__wrapped__`` attribute now always refers to the wrapped
706 function, even if that function defined a ``__wrapped__`` attribute.
707 (see :issue:`17482`)
708
709 .. versionchanged:: 3.12
710 The :attr:`~function.__type_params__` attribute is now copied by default.
711
712
713 .. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
714
715 This is a convenience function for invoking :func:`update_wrapper` as a
716 function decorator when defining a wrapper function. It is equivalent to
717 ``partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)``.
718 For example::
719
720 >>> from functools import wraps
721 >>> def my_decorator(f):
722 ... @wraps(f)
723 ... def wrapper(*args, **kwds):
724 ... print('Calling decorated function')
725 ... return f(*args, **kwds)
726 ... return wrapper
727 ...
728 >>> @my_decorator
729 ... def example():
730 ... """Docstring"""
731 ... print('Called example function')
732 ...
733 >>> example()
734 Calling decorated function
735 Called example function
736 >>> example.__name__
737 'example'
738 >>> example.__doc__
739 'Docstring'
740
741 Without the use of this decorator factory, the name of the example function
742 would have been ``'wrapper'``, and the docstring of the original :func:`!example`
743 would have been lost.
744
745
746 .. _partial-objects:
747
748 :class:`partial` Objects
749 ------------------------
750
751 :class:`partial` objects are callable objects created by :func:`partial`. They
752 have three read-only attributes:
753
754
755 .. attribute:: partial.func
756
757 A callable object or function. Calls to the :class:`partial` object will be
758 forwarded to :attr:`func` with new arguments and keywords.
759
760
761 .. attribute:: partial.args
762
763 The leftmost positional arguments that will be prepended to the positional
764 arguments provided to a :class:`partial` object call.
765
766
767 .. attribute:: partial.keywords
768
769 The keyword arguments that will be supplied when the :class:`partial` object is
770 called.
771
772 :class:`partial` objects are like :ref:`function objects <user-defined-funcs>`
773 in that they are callable, weak referenceable, and can have attributes.
774 There are some important differences. For instance, the
775 :attr:`~function.__name__` and :attr:`function.__doc__` attributes
776 are not created automatically. Also, :class:`partial` objects defined in
777 classes behave like static methods and do not transform into bound methods
778 during instance attribute look-up.