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 <scav@blueyonder.co.uk> 8.. moduleauthor:: Raymond Hettinger <python@rcn.com> 9.. moduleauthor:: Nick Coghlan <ncoghlan@gmail.com> 10.. moduleauthor:: Łukasz Langa <lukasz@langa.pl> 11.. moduleauthor:: Pablo Galindo <pablogsal@gmail.com> 12.. sectionauthor:: Peter Harris <scav@blueyonder.co.uk> 13 14**Source code:** :source:`Lib/functools.py` 15 16.. testsetup:: default 17 18 import functools 19 from functools import * 20 21-------------- 22 23The :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 27The :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 :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 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 :func:`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 :func:`cached_property` are somewhat different from 82 :func:`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 :func:`cached_property` can also be achieved by 115 stacking :func:`property` on top of :func:`lru_cache`. See 116 :ref:`faq-cache-method-calls` for more details on how this differs from :func:`cached_property`. 117 118 .. versionadded:: 3.8 119 120 .. versionchanged:: 3.12 121 Prior to Python 3.12, ``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 be 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 To help measure the effectiveness of the cache and tune the *maxsize* 203 parameter, the wrapped function is instrumented with a :func:`cache_info` 204 function that returns a :term:`named tuple` showing *hits*, *misses*, 205 *maxsize* and *currsize*. 206 207 The decorator also provides a :func:`cache_clear` function for clearing or 208 invalidating the cache. 209 210 The original underlying function is accessible through the 211 :attr:`__wrapped__` attribute. This is useful for introspection, for 212 bypassing the cache, or for rewrapping the function with a different cache. 213 214 The cache keeps references to the arguments and return values until they age 215 out of the cache or until the cache is cleared. 216 217 If a method is cached, the ``self`` instance argument is included in the 218 cache. See :ref:`faq-cache-method-calls` 219 220 An `LRU (least recently used) cache 221 <https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_Recently_Used_(LRU)>`_ 222 works best when the most recent calls are the best predictors of upcoming 223 calls (for example, the most popular articles on a news server tend to 224 change each day). The cache's size limit assures that the cache does not 225 grow without bound on long-running processes such as web servers. 226 227 In general, the LRU cache should only be used when you want to reuse 228 previously computed values. Accordingly, it doesn't make sense to cache 229 functions with side-effects, functions that need to create 230 distinct mutable objects on each call (such as generators and async functions), 231 or impure functions such as time() or random(). 232 233 Example of an LRU cache for static web content:: 234 235 @lru_cache(maxsize=32) 236 def get_pep(num): 237 'Retrieve text of a Python Enhancement Proposal' 238 resource = f'https://peps.python.org/pep-{num:04d}' 239 try: 240 with urllib.request.urlopen(resource) as s: 241 return s.read() 242 except urllib.error.HTTPError: 243 return 'Not Found' 244 245 >>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991: 246 ... pep = get_pep(n) 247 ... print(n, len(pep)) 248 249 >>> get_pep.cache_info() 250 CacheInfo(hits=3, misses=8, maxsize=32, currsize=8) 251 252 Example of efficiently computing 253 `Fibonacci numbers <https://en.wikipedia.org/wiki/Fibonacci_number>`_ 254 using a cache to implement a 255 `dynamic programming <https://en.wikipedia.org/wiki/Dynamic_programming>`_ 256 technique:: 257 258 @lru_cache(maxsize=None) 259 def fib(n): 260 if n < 2: 261 return n 262 return fib(n-1) + fib(n-2) 263 264 >>> [fib(n) for n in range(16)] 265 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] 266 267 >>> fib.cache_info() 268 CacheInfo(hits=28, misses=16, maxsize=None, currsize=16) 269 270 .. versionadded:: 3.2 271 272 .. versionchanged:: 3.3 273 Added the *typed* option. 274 275 .. versionchanged:: 3.8 276 Added the *user_function* option. 277 278 .. versionchanged:: 3.9 279 Added the function :func:`!cache_parameters` 280 281.. decorator:: total_ordering 282 283 Given a class defining one or more rich comparison ordering methods, this 284 class decorator supplies the rest. This simplifies the effort involved 285 in specifying all of the possible rich comparison operations: 286 287 The class must define one of :meth:`__lt__`, :meth:`__le__`, 288 :meth:`__gt__`, or :meth:`__ge__`. 289 In addition, the class should supply an :meth:`__eq__` method. 290 291 For example:: 292 293 @total_ordering 294 class Student: 295 def _is_valid_operand(self, other): 296 return (hasattr(other, "lastname") and 297 hasattr(other, "firstname")) 298 def __eq__(self, other): 299 if not self._is_valid_operand(other): 300 return NotImplemented 301 return ((self.lastname.lower(), self.firstname.lower()) == 302 (other.lastname.lower(), other.firstname.lower())) 303 def __lt__(self, other): 304 if not self._is_valid_operand(other): 305 return NotImplemented 306 return ((self.lastname.lower(), self.firstname.lower()) < 307 (other.lastname.lower(), other.firstname.lower())) 308 309 .. note:: 310 311 While this decorator makes it easy to create well behaved totally 312 ordered types, it *does* come at the cost of slower execution and 313 more complex stack traces for the derived comparison methods. If 314 performance benchmarking indicates this is a bottleneck for a given 315 application, implementing all six rich comparison methods instead is 316 likely to provide an easy speed boost. 317 318 .. note:: 319 320 This decorator makes no attempt to override methods that have been 321 declared in the class *or its superclasses*. Meaning that if a 322 superclass defines a comparison operator, *total_ordering* will not 323 implement it again, even if the original method is abstract. 324 325 .. versionadded:: 3.2 326 327 .. versionchanged:: 3.4 328 Returning ``NotImplemented`` from the underlying comparison function for 329 unrecognised types is now supported. 330 331.. function:: partial(func, /, *args, **keywords) 332 333 Return a new :ref:`partial object<partial-objects>` which when called 334 will behave like *func* called with the positional arguments *args* 335 and keyword arguments *keywords*. If more arguments are supplied to the 336 call, they are appended to *args*. If additional keyword arguments are 337 supplied, they extend and override *keywords*. 338 Roughly equivalent to:: 339 340 def partial(func, /, *args, **keywords): 341 def newfunc(*fargs, **fkeywords): 342 newkeywords = {**keywords, **fkeywords} 343 return func(*args, *fargs, **newkeywords) 344 newfunc.func = func 345 newfunc.args = args 346 newfunc.keywords = keywords 347 return newfunc 348 349 The :func:`partial` is used for partial function application which "freezes" 350 some portion of a function's arguments and/or keywords resulting in a new object 351 with a simplified signature. For example, :func:`partial` can be used to create 352 a callable that behaves like the :func:`int` function where the *base* argument 353 defaults to two: 354 355 >>> from functools import partial 356 >>> basetwo = partial(int, base=2) 357 >>> basetwo.__doc__ = 'Convert base 2 string to an int.' 358 >>> basetwo('10010') 359 18 360 361 362.. class:: partialmethod(func, /, *args, **keywords) 363 364 Return a new :class:`partialmethod` descriptor which behaves 365 like :class:`partial` except that it is designed to be used as a method 366 definition rather than being directly callable. 367 368 *func* must be a :term:`descriptor` or a callable (objects which are both, 369 like normal functions, are handled as descriptors). 370 371 When *func* is a descriptor (such as a normal Python function, 372 :func:`classmethod`, :func:`staticmethod`, :func:`abstractmethod` or 373 another instance of :class:`partialmethod`), calls to ``__get__`` are 374 delegated to the underlying descriptor, and an appropriate 375 :ref:`partial object<partial-objects>` returned as the result. 376 377 When *func* is a non-descriptor callable, an appropriate bound method is 378 created dynamically. This behaves like a normal Python function when 379 used as a method: the *self* argument will be inserted as the first 380 positional argument, even before the *args* and *keywords* supplied to 381 the :class:`partialmethod` constructor. 382 383 Example:: 384 385 >>> class Cell: 386 ... def __init__(self): 387 ... self._alive = False 388 ... @property 389 ... def alive(self): 390 ... return self._alive 391 ... def set_state(self, state): 392 ... self._alive = bool(state) 393 ... set_alive = partialmethod(set_state, True) 394 ... set_dead = partialmethod(set_state, False) 395 ... 396 >>> c = Cell() 397 >>> c.alive 398 False 399 >>> c.set_alive() 400 >>> c.alive 401 True 402 403 .. versionadded:: 3.4 404 405 406.. function:: reduce(function, iterable[, initial], /) 407 408 Apply *function* of two arguments cumulatively to the items of *iterable*, from 409 left to right, so as to reduce the iterable to a single value. For example, 410 ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``. 411 The left argument, *x*, is the accumulated value and the right argument, *y*, is 412 the update value from the *iterable*. If the optional *initial* is present, 413 it is placed before the items of the iterable in the calculation, and serves as 414 a default when the iterable is empty. If *initial* is not given and 415 *iterable* contains only one item, the first item is returned. 416 417 Roughly equivalent to:: 418 419 initial_missing = object() 420 421 def reduce(function, iterable, initial=initial_missing, /): 422 it = iter(iterable) 423 if initial is initial_missing: 424 value = next(it) 425 else: 426 value = initial 427 for element in it: 428 value = function(value, element) 429 return value 430 431 See :func:`itertools.accumulate` for an iterator that yields all intermediate 432 values. 433 434.. decorator:: singledispatch 435 436 Transform a function into a :term:`single-dispatch <single 437 dispatch>` :term:`generic function`. 438 439 To define a generic function, decorate it with the ``@singledispatch`` 440 decorator. When defining a function using ``@singledispatch``, note that the 441 dispatch happens on the type of the first argument:: 442 443 >>> from functools import singledispatch 444 >>> @singledispatch 445 ... def fun(arg, verbose=False): 446 ... if verbose: 447 ... print("Let me just say,", end=" ") 448 ... print(arg) 449 450 To add overloaded implementations to the function, use the :func:`register` 451 attribute of the generic function, which can be used as a decorator. For 452 functions annotated with types, the decorator will infer the type of the 453 first argument automatically:: 454 455 >>> @fun.register 456 ... def _(arg: int, verbose=False): 457 ... if verbose: 458 ... print("Strength in numbers, eh?", end=" ") 459 ... print(arg) 460 ... 461 >>> @fun.register 462 ... def _(arg: list, verbose=False): 463 ... if verbose: 464 ... print("Enumerate this:") 465 ... for i, elem in enumerate(arg): 466 ... print(i, elem) 467 468 :data:`types.UnionType` and :data:`typing.Union` can also be used:: 469 470 >>> @fun.register 471 ... def _(arg: int | float, verbose=False): 472 ... if verbose: 473 ... print("Strength in numbers, eh?", end=" ") 474 ... print(arg) 475 ... 476 >>> from typing import Union 477 >>> @fun.register 478 ... def _(arg: Union[list, set], verbose=False): 479 ... if verbose: 480 ... print("Enumerate this:") 481 ... for i, elem in enumerate(arg): 482 ... print(i, elem) 483 ... 484 485 For code which doesn't use type annotations, the appropriate type 486 argument can be passed explicitly to the decorator itself:: 487 488 >>> @fun.register(complex) 489 ... def _(arg, verbose=False): 490 ... if verbose: 491 ... print("Better than complicated.", end=" ") 492 ... print(arg.real, arg.imag) 493 ... 494 495 For code that dispatches on a collections type (e.g., ``list``), but wants 496 to typehint the items of the collection (e.g., ``list[int]``), the 497 dispatch type should be passed explicitly to the decorator itself with the 498 typehint going into the function definition:: 499 500 >>> @fun.register(list) 501 ... def _(arg: list[int], verbose=False): 502 ... if verbose: 503 ... print("Enumerate this:") 504 ... for i, elem in enumerate(arg): 505 ... print(i, elem) 506 507 .. note:: 508 509 At runtime the function will dispatch on an instance of a list regardless 510 of the type contained within the list i.e. ``[1,2,3]`` will be 511 dispatched the same as ``["foo", "bar", "baz"]``. The annotation 512 provided in this example is for static type checkers only and has no 513 runtime impact. 514 515 To enable registering :term:`lambdas<lambda>` and pre-existing functions, 516 the :func:`register` attribute can also be used in a functional form:: 517 518 >>> def nothing(arg, verbose=False): 519 ... print("Nothing.") 520 ... 521 >>> fun.register(type(None), nothing) 522 523 The :func:`register` attribute returns the undecorated function. This 524 enables decorator stacking, :mod:`pickling<pickle>`, and the creation 525 of unit tests for each variant independently:: 526 527 >>> @fun.register(float) 528 ... @fun.register(Decimal) 529 ... def fun_num(arg, verbose=False): 530 ... if verbose: 531 ... print("Half of your number:", end=" ") 532 ... print(arg / 2) 533 ... 534 >>> fun_num is fun 535 False 536 537 When called, the generic function dispatches on the type of the first 538 argument:: 539 540 >>> fun("Hello, world.") 541 Hello, world. 542 >>> fun("test.", verbose=True) 543 Let me just say, test. 544 >>> fun(42, verbose=True) 545 Strength in numbers, eh? 42 546 >>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True) 547 Enumerate this: 548 0 spam 549 1 spam 550 2 eggs 551 3 spam 552 >>> fun(None) 553 Nothing. 554 >>> fun(1.23) 555 0.615 556 557 Where there is no registered implementation for a specific type, its 558 method resolution order is used to find a more generic implementation. 559 The original function decorated with ``@singledispatch`` is registered 560 for the base :class:`object` type, which means it is used if no better 561 implementation is found. 562 563 If an implementation is registered to an :term:`abstract base class`, 564 virtual subclasses of the base class will be dispatched to that 565 implementation:: 566 567 >>> from collections.abc import Mapping 568 >>> @fun.register 569 ... def _(arg: Mapping, verbose=False): 570 ... if verbose: 571 ... print("Keys & Values") 572 ... for key, value in arg.items(): 573 ... print(key, "=>", value) 574 ... 575 >>> fun({"a": "b"}) 576 a => b 577 578 To check which implementation the generic function will choose for 579 a given type, use the ``dispatch()`` attribute:: 580 581 >>> fun.dispatch(float) 582 <function fun_num at 0x1035a2840> 583 >>> fun.dispatch(dict) # note: default implementation 584 <function fun at 0x103fe0000> 585 586 To access all registered implementations, use the read-only ``registry`` 587 attribute:: 588 589 >>> fun.registry.keys() 590 dict_keys([<class 'NoneType'>, <class 'int'>, <class 'object'>, 591 <class 'decimal.Decimal'>, <class 'list'>, 592 <class 'float'>]) 593 >>> fun.registry[float] 594 <function fun_num at 0x1035a2840> 595 >>> fun.registry[object] 596 <function fun at 0x103fe0000> 597 598 .. versionadded:: 3.4 599 600 .. versionchanged:: 3.7 601 The :func:`register` attribute now supports using type annotations. 602 603 .. versionchanged:: 3.11 604 The :func:`register` attribute now supports :data:`types.UnionType` 605 and :data:`typing.Union` as type annotations. 606 607 608.. class:: singledispatchmethod(func) 609 610 Transform a method into a :term:`single-dispatch <single 611 dispatch>` :term:`generic function`. 612 613 To define a generic method, decorate it with the ``@singledispatchmethod`` 614 decorator. When defining a function using ``@singledispatchmethod``, note 615 that the dispatch happens on the type of the first non-*self* or non-*cls* 616 argument:: 617 618 class Negator: 619 @singledispatchmethod 620 def neg(self, arg): 621 raise NotImplementedError("Cannot negate a") 622 623 @neg.register 624 def _(self, arg: int): 625 return -arg 626 627 @neg.register 628 def _(self, arg: bool): 629 return not arg 630 631 ``@singledispatchmethod`` supports nesting with other decorators such as 632 :func:`@classmethod<classmethod>`. Note that to allow for 633 ``dispatcher.register``, ``singledispatchmethod`` must be the *outer most* 634 decorator. Here is the ``Negator`` class with the ``neg`` methods bound to 635 the class, rather than an instance of the class:: 636 637 class Negator: 638 @singledispatchmethod 639 @classmethod 640 def neg(cls, arg): 641 raise NotImplementedError("Cannot negate a") 642 643 @neg.register 644 @classmethod 645 def _(cls, arg: int): 646 return -arg 647 648 @neg.register 649 @classmethod 650 def _(cls, arg: bool): 651 return not arg 652 653 The same pattern can be used for other similar decorators: 654 :func:`@staticmethod<staticmethod>`, 655 :func:`@abstractmethod<abc.abstractmethod>`, and others. 656 657 .. versionadded:: 3.8 658 659 660.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES) 661 662 Update a *wrapper* function to look like the *wrapped* function. The optional 663 arguments are tuples to specify which attributes of the original function are 664 assigned directly to the matching attributes on the wrapper function and which 665 attributes of the wrapper function are updated with the corresponding attributes 666 from the original function. The default values for these arguments are the 667 module level constants ``WRAPPER_ASSIGNMENTS`` (which assigns to the wrapper 668 function's :attr:`~function.__module__`, :attr:`~function.__name__`, 669 :attr:`~function.__qualname__`, :attr:`~function.__annotations__`, 670 :attr:`~function.__type_params__`, and :attr:`~function.__doc__`, the 671 documentation string) and ``WRAPPER_UPDATES`` (which updates the wrapper 672 function's :attr:`~function.__dict__`, i.e. the instance dictionary). 673 674 To allow access to the original function for introspection and other purposes 675 (e.g. bypassing a caching decorator such as :func:`lru_cache`), this function 676 automatically adds a ``__wrapped__`` attribute to the wrapper that refers to 677 the function being wrapped. 678 679 The main intended use for this function is in :term:`decorator` functions which 680 wrap the decorated function and return the wrapper. If the wrapper function is 681 not updated, the metadata of the returned function will reflect the wrapper 682 definition rather than the original function definition, which is typically less 683 than helpful. 684 685 :func:`update_wrapper` may be used with callables other than functions. Any 686 attributes named in *assigned* or *updated* that are missing from the object 687 being wrapped are ignored (i.e. this function will not attempt to set them 688 on the wrapper function). :exc:`AttributeError` is still raised if the 689 wrapper function itself is missing any attributes named in *updated*. 690 691 .. versionchanged:: 3.2 692 The ``__wrapped__`` attribute is now automatically added. 693 The :attr:`~function.__annotations__` attribute is now copied by default. 694 Missing attributes no longer trigger an :exc:`AttributeError`. 695 696 .. versionchanged:: 3.4 697 The ``__wrapped__`` attribute now always refers to the wrapped 698 function, even if that function defined a ``__wrapped__`` attribute. 699 (see :issue:`17482`) 700 701 .. versionchanged:: 3.12 702 The :attr:`~function.__type_params__` attribute is now copied by default. 703 704 705.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES) 706 707 This is a convenience function for invoking :func:`update_wrapper` as a 708 function decorator when defining a wrapper function. It is equivalent to 709 ``partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)``. 710 For example:: 711 712 >>> from functools import wraps 713 >>> def my_decorator(f): 714 ... @wraps(f) 715 ... def wrapper(*args, **kwds): 716 ... print('Calling decorated function') 717 ... return f(*args, **kwds) 718 ... return wrapper 719 ... 720 >>> @my_decorator 721 ... def example(): 722 ... """Docstring""" 723 ... print('Called example function') 724 ... 725 >>> example() 726 Calling decorated function 727 Called example function 728 >>> example.__name__ 729 'example' 730 >>> example.__doc__ 731 'Docstring' 732 733 Without the use of this decorator factory, the name of the example function 734 would have been ``'wrapper'``, and the docstring of the original :func:`example` 735 would have been lost. 736 737 738.. _partial-objects: 739 740:class:`partial` Objects 741------------------------ 742 743:class:`partial` objects are callable objects created by :func:`partial`. They 744have three read-only attributes: 745 746 747.. attribute:: partial.func 748 749 A callable object or function. Calls to the :class:`partial` object will be 750 forwarded to :attr:`func` with new arguments and keywords. 751 752 753.. attribute:: partial.args 754 755 The leftmost positional arguments that will be prepended to the positional 756 arguments provided to a :class:`partial` object call. 757 758 759.. attribute:: partial.keywords 760 761 The keyword arguments that will be supplied when the :class:`partial` object is 762 called. 763 764:class:`partial` objects are like :ref:`function objects <user-defined-funcs>` 765in that they are callable, weak referenceable, and can have attributes. 766There are some important differences. For instance, the 767:attr:`~function.__name__` and :attr:`function.__doc__` attributes 768are not created automatically. Also, :class:`partial` objects defined in 769classes behave like static methods and do not transform into bound methods 770during instance attribute look-up. 771