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