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.. sectionauthor:: Peter Harris <scav@blueyonder.co.uk> 12 13**Source code:** :source:`Lib/functools.py` 14 15-------------- 16 17The :mod:`functools` module is for higher-order functions: functions that act on 18or return other functions. In general, any callable object can be treated as a 19function for the purposes of this module. 20 21The :mod:`functools` module defines the following functions: 22 23.. decorator:: cached_property(func) 24 25 Transform a method of a class into a property whose value is computed once 26 and then cached as a normal attribute for the life of the instance. Similar 27 to :func:`property`, with the addition of caching. Useful for expensive 28 computed properties of instances that are otherwise effectively immutable. 29 30 Example:: 31 32 class DataSet: 33 def __init__(self, sequence_of_numbers): 34 self._data = sequence_of_numbers 35 36 @cached_property 37 def stdev(self): 38 return statistics.stdev(self._data) 39 40 @cached_property 41 def variance(self): 42 return statistics.variance(self._data) 43 44 .. versionadded:: 3.8 45 46 .. note:: 47 48 This decorator requires that the ``__dict__`` attribute on each instance 49 be a mutable mapping. This means it will not work with some types, such as 50 metaclasses (since the ``__dict__`` attributes on type instances are 51 read-only proxies for the class namespace), and those that specify 52 ``__slots__`` without including ``__dict__`` as one of the defined slots 53 (as such classes don't provide a ``__dict__`` attribute at all). 54 55 56.. function:: cmp_to_key(func) 57 58 Transform an old-style comparison function to a :term:`key function`. Used 59 with tools that accept key functions (such as :func:`sorted`, :func:`min`, 60 :func:`max`, :func:`heapq.nlargest`, :func:`heapq.nsmallest`, 61 :func:`itertools.groupby`). This function is primarily used as a transition 62 tool for programs being converted from Python 2 which supported the use of 63 comparison functions. 64 65 A comparison function is any callable that accept two arguments, compares them, 66 and returns a negative number for less-than, zero for equality, or a positive 67 number for greater-than. A key function is a callable that accepts one 68 argument and returns another value to be used as the sort key. 69 70 Example:: 71 72 sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order 73 74 For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`. 75 76 .. versionadded:: 3.2 77 78 79.. decorator:: lru_cache(user_function) 80 lru_cache(maxsize=128, typed=False) 81 82 Decorator to wrap a function with a memoizing callable that saves up to the 83 *maxsize* most recent calls. It can save time when an expensive or I/O bound 84 function is periodically called with the same arguments. 85 86 Since a dictionary is used to cache results, the positional and keyword 87 arguments to the function must be hashable. 88 89 Distinct argument patterns may be considered to be distinct calls with 90 separate cache entries. For example, `f(a=1, b=2)` and `f(b=2, a=1)` 91 differ in their keyword argument order and may have two separate cache 92 entries. 93 94 If *user_function* is specified, it must be a callable. This allows the 95 *lru_cache* decorator to be applied directly to a user function, leaving 96 the *maxsize* at its default value of 128:: 97 98 @lru_cache 99 def count_vowels(sentence): 100 sentence = sentence.casefold() 101 return sum(sentence.count(vowel) for vowel in 'aeiou') 102 103 If *maxsize* is set to ``None``, the LRU feature is disabled and the cache can 104 grow without bound. 105 106 If *typed* is set to true, function arguments of different types will be 107 cached separately. For example, ``f(3)`` and ``f(3.0)`` will be treated 108 as distinct calls with distinct results. 109 110 To help measure the effectiveness of the cache and tune the *maxsize* 111 parameter, the wrapped function is instrumented with a :func:`cache_info` 112 function that returns a :term:`named tuple` showing *hits*, *misses*, 113 *maxsize* and *currsize*. In a multi-threaded environment, the hits 114 and misses are approximate. 115 116 The decorator also provides a :func:`cache_clear` function for clearing or 117 invalidating the cache. 118 119 The original underlying function is accessible through the 120 :attr:`__wrapped__` attribute. This is useful for introspection, for 121 bypassing the cache, or for rewrapping the function with a different cache. 122 123 An `LRU (least recently used) cache 124 <https://en.wikipedia.org/wiki/Cache_algorithms#Examples>`_ works 125 best when the most recent calls are the best predictors of upcoming calls (for 126 example, the most popular articles on a news server tend to change each day). 127 The cache's size limit assures that the cache does not grow without bound on 128 long-running processes such as web servers. 129 130 In general, the LRU cache should only be used when you want to reuse 131 previously computed values. Accordingly, it doesn't make sense to cache 132 functions with side-effects, functions that need to create distinct mutable 133 objects on each call, or impure functions such as time() or random(). 134 135 Example of an LRU cache for static web content:: 136 137 @lru_cache(maxsize=32) 138 def get_pep(num): 139 'Retrieve text of a Python Enhancement Proposal' 140 resource = 'http://www.python.org/dev/peps/pep-%04d/' % num 141 try: 142 with urllib.request.urlopen(resource) as s: 143 return s.read() 144 except urllib.error.HTTPError: 145 return 'Not Found' 146 147 >>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991: 148 ... pep = get_pep(n) 149 ... print(n, len(pep)) 150 151 >>> get_pep.cache_info() 152 CacheInfo(hits=3, misses=8, maxsize=32, currsize=8) 153 154 Example of efficiently computing 155 `Fibonacci numbers <https://en.wikipedia.org/wiki/Fibonacci_number>`_ 156 using a cache to implement a 157 `dynamic programming <https://en.wikipedia.org/wiki/Dynamic_programming>`_ 158 technique:: 159 160 @lru_cache(maxsize=None) 161 def fib(n): 162 if n < 2: 163 return n 164 return fib(n-1) + fib(n-2) 165 166 >>> [fib(n) for n in range(16)] 167 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] 168 169 >>> fib.cache_info() 170 CacheInfo(hits=28, misses=16, maxsize=None, currsize=16) 171 172 .. versionadded:: 3.2 173 174 .. versionchanged:: 3.3 175 Added the *typed* option. 176 177 .. versionchanged:: 3.8 178 Added the *user_function* option. 179 180.. decorator:: total_ordering 181 182 Given a class defining one or more rich comparison ordering methods, this 183 class decorator supplies the rest. This simplifies the effort involved 184 in specifying all of the possible rich comparison operations: 185 186 The class must define one of :meth:`__lt__`, :meth:`__le__`, 187 :meth:`__gt__`, or :meth:`__ge__`. 188 In addition, the class should supply an :meth:`__eq__` method. 189 190 For example:: 191 192 @total_ordering 193 class Student: 194 def _is_valid_operand(self, other): 195 return (hasattr(other, "lastname") and 196 hasattr(other, "firstname")) 197 def __eq__(self, other): 198 if not self._is_valid_operand(other): 199 return NotImplemented 200 return ((self.lastname.lower(), self.firstname.lower()) == 201 (other.lastname.lower(), other.firstname.lower())) 202 def __lt__(self, other): 203 if not self._is_valid_operand(other): 204 return NotImplemented 205 return ((self.lastname.lower(), self.firstname.lower()) < 206 (other.lastname.lower(), other.firstname.lower())) 207 208 .. note:: 209 210 While this decorator makes it easy to create well behaved totally 211 ordered types, it *does* come at the cost of slower execution and 212 more complex stack traces for the derived comparison methods. If 213 performance benchmarking indicates this is a bottleneck for a given 214 application, implementing all six rich comparison methods instead is 215 likely to provide an easy speed boost. 216 217 .. versionadded:: 3.2 218 219 .. versionchanged:: 3.4 220 Returning NotImplemented from the underlying comparison function for 221 unrecognised types is now supported. 222 223.. function:: partial(func, /, *args, **keywords) 224 225 Return a new :ref:`partial object<partial-objects>` which when called 226 will behave like *func* called with the positional arguments *args* 227 and keyword arguments *keywords*. If more arguments are supplied to the 228 call, they are appended to *args*. If additional keyword arguments are 229 supplied, they extend and override *keywords*. 230 Roughly equivalent to:: 231 232 def partial(func, /, *args, **keywords): 233 def newfunc(*fargs, **fkeywords): 234 newkeywords = {**keywords, **fkeywords} 235 return func(*args, *fargs, **newkeywords) 236 newfunc.func = func 237 newfunc.args = args 238 newfunc.keywords = keywords 239 return newfunc 240 241 The :func:`partial` is used for partial function application which "freezes" 242 some portion of a function's arguments and/or keywords resulting in a new object 243 with a simplified signature. For example, :func:`partial` can be used to create 244 a callable that behaves like the :func:`int` function where the *base* argument 245 defaults to two: 246 247 >>> from functools import partial 248 >>> basetwo = partial(int, base=2) 249 >>> basetwo.__doc__ = 'Convert base 2 string to an int.' 250 >>> basetwo('10010') 251 18 252 253 254.. class:: partialmethod(func, /, *args, **keywords) 255 256 Return a new :class:`partialmethod` descriptor which behaves 257 like :class:`partial` except that it is designed to be used as a method 258 definition rather than being directly callable. 259 260 *func* must be a :term:`descriptor` or a callable (objects which are both, 261 like normal functions, are handled as descriptors). 262 263 When *func* is a descriptor (such as a normal Python function, 264 :func:`classmethod`, :func:`staticmethod`, :func:`abstractmethod` or 265 another instance of :class:`partialmethod`), calls to ``__get__`` are 266 delegated to the underlying descriptor, and an appropriate 267 :ref:`partial object<partial-objects>` returned as the result. 268 269 When *func* is a non-descriptor callable, an appropriate bound method is 270 created dynamically. This behaves like a normal Python function when 271 used as a method: the *self* argument will be inserted as the first 272 positional argument, even before the *args* and *keywords* supplied to 273 the :class:`partialmethod` constructor. 274 275 Example:: 276 277 >>> class Cell(object): 278 ... def __init__(self): 279 ... self._alive = False 280 ... @property 281 ... def alive(self): 282 ... return self._alive 283 ... def set_state(self, state): 284 ... self._alive = bool(state) 285 ... set_alive = partialmethod(set_state, True) 286 ... set_dead = partialmethod(set_state, False) 287 ... 288 >>> c = Cell() 289 >>> c.alive 290 False 291 >>> c.set_alive() 292 >>> c.alive 293 True 294 295 .. versionadded:: 3.4 296 297 298.. function:: reduce(function, iterable[, initializer]) 299 300 Apply *function* of two arguments cumulatively to the items of *iterable*, from 301 left to right, so as to reduce the iterable to a single value. For example, 302 ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``. 303 The left argument, *x*, is the accumulated value and the right argument, *y*, is 304 the update value from the *iterable*. If the optional *initializer* is present, 305 it is placed before the items of the iterable in the calculation, and serves as 306 a default when the iterable is empty. If *initializer* is not given and 307 *iterable* contains only one item, the first item is returned. 308 309 Roughly equivalent to:: 310 311 def reduce(function, iterable, initializer=None): 312 it = iter(iterable) 313 if initializer is None: 314 value = next(it) 315 else: 316 value = initializer 317 for element in it: 318 value = function(value, element) 319 return value 320 321 See :func:`itertools.accumulate` for an iterator that yields all intermediate 322 values. 323 324.. decorator:: singledispatch 325 326 Transform a function into a :term:`single-dispatch <single 327 dispatch>` :term:`generic function`. 328 329 To define a generic function, decorate it with the ``@singledispatch`` 330 decorator. Note that the dispatch happens on the type of the first argument, 331 create your function accordingly:: 332 333 >>> from functools import singledispatch 334 >>> @singledispatch 335 ... def fun(arg, verbose=False): 336 ... if verbose: 337 ... print("Let me just say,", end=" ") 338 ... print(arg) 339 340 To add overloaded implementations to the function, use the :func:`register` 341 attribute of the generic function. It is a decorator. For functions 342 annotated with types, the decorator will infer the type of the first 343 argument automatically:: 344 345 >>> @fun.register 346 ... def _(arg: int, verbose=False): 347 ... if verbose: 348 ... print("Strength in numbers, eh?", end=" ") 349 ... print(arg) 350 ... 351 >>> @fun.register 352 ... def _(arg: list, verbose=False): 353 ... if verbose: 354 ... print("Enumerate this:") 355 ... for i, elem in enumerate(arg): 356 ... print(i, elem) 357 358 For code which doesn't use type annotations, the appropriate type 359 argument can be passed explicitly to the decorator itself:: 360 361 >>> @fun.register(complex) 362 ... def _(arg, verbose=False): 363 ... if verbose: 364 ... print("Better than complicated.", end=" ") 365 ... print(arg.real, arg.imag) 366 ... 367 368 369 To enable registering lambdas and pre-existing functions, the 370 :func:`register` attribute can be used in a functional form:: 371 372 >>> def nothing(arg, verbose=False): 373 ... print("Nothing.") 374 ... 375 >>> fun.register(type(None), nothing) 376 377 The :func:`register` attribute returns the undecorated function which 378 enables decorator stacking, pickling, as well as creating unit tests for 379 each variant independently:: 380 381 >>> @fun.register(float) 382 ... @fun.register(Decimal) 383 ... def fun_num(arg, verbose=False): 384 ... if verbose: 385 ... print("Half of your number:", end=" ") 386 ... print(arg / 2) 387 ... 388 >>> fun_num is fun 389 False 390 391 When called, the generic function dispatches on the type of the first 392 argument:: 393 394 >>> fun("Hello, world.") 395 Hello, world. 396 >>> fun("test.", verbose=True) 397 Let me just say, test. 398 >>> fun(42, verbose=True) 399 Strength in numbers, eh? 42 400 >>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True) 401 Enumerate this: 402 0 spam 403 1 spam 404 2 eggs 405 3 spam 406 >>> fun(None) 407 Nothing. 408 >>> fun(1.23) 409 0.615 410 411 Where there is no registered implementation for a specific type, its 412 method resolution order is used to find a more generic implementation. 413 The original function decorated with ``@singledispatch`` is registered 414 for the base ``object`` type, which means it is used if no better 415 implementation is found. 416 417 To check which implementation will the generic function choose for 418 a given type, use the ``dispatch()`` attribute:: 419 420 >>> fun.dispatch(float) 421 <function fun_num at 0x1035a2840> 422 >>> fun.dispatch(dict) # note: default implementation 423 <function fun at 0x103fe0000> 424 425 To access all registered implementations, use the read-only ``registry`` 426 attribute:: 427 428 >>> fun.registry.keys() 429 dict_keys([<class 'NoneType'>, <class 'int'>, <class 'object'>, 430 <class 'decimal.Decimal'>, <class 'list'>, 431 <class 'float'>]) 432 >>> fun.registry[float] 433 <function fun_num at 0x1035a2840> 434 >>> fun.registry[object] 435 <function fun at 0x103fe0000> 436 437 .. versionadded:: 3.4 438 439 .. versionchanged:: 3.7 440 The :func:`register` attribute supports using type annotations. 441 442 443.. class:: singledispatchmethod(func) 444 445 Transform a method into a :term:`single-dispatch <single 446 dispatch>` :term:`generic function`. 447 448 To define a generic method, decorate it with the ``@singledispatchmethod`` 449 decorator. Note that the dispatch happens on the type of the first non-self 450 or non-cls argument, create your function accordingly:: 451 452 class Negator: 453 @singledispatchmethod 454 def neg(self, arg): 455 raise NotImplementedError("Cannot negate a") 456 457 @neg.register 458 def _(self, arg: int): 459 return -arg 460 461 @neg.register 462 def _(self, arg: bool): 463 return not arg 464 465 ``@singledispatchmethod`` supports nesting with other decorators such as 466 ``@classmethod``. Note that to allow for ``dispatcher.register``, 467 ``singledispatchmethod`` must be the *outer most* decorator. Here is the 468 ``Negator`` class with the ``neg`` methods being class bound:: 469 470 class Negator: 471 @singledispatchmethod 472 @classmethod 473 def neg(cls, arg): 474 raise NotImplementedError("Cannot negate a") 475 476 @neg.register 477 @classmethod 478 def _(cls, arg: int): 479 return -arg 480 481 @neg.register 482 @classmethod 483 def _(cls, arg: bool): 484 return not arg 485 486 The same pattern can be used for other similar decorators: ``staticmethod``, 487 ``abstractmethod``, and others. 488 489 .. versionadded:: 3.8 490 491 492.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES) 493 494 Update a *wrapper* function to look like the *wrapped* function. The optional 495 arguments are tuples to specify which attributes of the original function are 496 assigned directly to the matching attributes on the wrapper function and which 497 attributes of the wrapper function are updated with the corresponding attributes 498 from the original function. The default values for these arguments are the 499 module level constants ``WRAPPER_ASSIGNMENTS`` (which assigns to the wrapper 500 function's ``__module__``, ``__name__``, ``__qualname__``, ``__annotations__`` 501 and ``__doc__``, the documentation string) and ``WRAPPER_UPDATES`` (which 502 updates the wrapper function's ``__dict__``, i.e. the instance dictionary). 503 504 To allow access to the original function for introspection and other purposes 505 (e.g. bypassing a caching decorator such as :func:`lru_cache`), this function 506 automatically adds a ``__wrapped__`` attribute to the wrapper that refers to 507 the function being wrapped. 508 509 The main intended use for this function is in :term:`decorator` functions which 510 wrap the decorated function and return the wrapper. If the wrapper function is 511 not updated, the metadata of the returned function will reflect the wrapper 512 definition rather than the original function definition, which is typically less 513 than helpful. 514 515 :func:`update_wrapper` may be used with callables other than functions. Any 516 attributes named in *assigned* or *updated* that are missing from the object 517 being wrapped are ignored (i.e. this function will not attempt to set them 518 on the wrapper function). :exc:`AttributeError` is still raised if the 519 wrapper function itself is missing any attributes named in *updated*. 520 521 .. versionadded:: 3.2 522 Automatic addition of the ``__wrapped__`` attribute. 523 524 .. versionadded:: 3.2 525 Copying of the ``__annotations__`` attribute by default. 526 527 .. versionchanged:: 3.2 528 Missing attributes no longer trigger an :exc:`AttributeError`. 529 530 .. versionchanged:: 3.4 531 The ``__wrapped__`` attribute now always refers to the wrapped 532 function, even if that function defined a ``__wrapped__`` attribute. 533 (see :issue:`17482`) 534 535 536.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES) 537 538 This is a convenience function for invoking :func:`update_wrapper` as a 539 function decorator when defining a wrapper function. It is equivalent to 540 ``partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)``. 541 For example:: 542 543 >>> from functools import wraps 544 >>> def my_decorator(f): 545 ... @wraps(f) 546 ... def wrapper(*args, **kwds): 547 ... print('Calling decorated function') 548 ... return f(*args, **kwds) 549 ... return wrapper 550 ... 551 >>> @my_decorator 552 ... def example(): 553 ... """Docstring""" 554 ... print('Called example function') 555 ... 556 >>> example() 557 Calling decorated function 558 Called example function 559 >>> example.__name__ 560 'example' 561 >>> example.__doc__ 562 'Docstring' 563 564 Without the use of this decorator factory, the name of the example function 565 would have been ``'wrapper'``, and the docstring of the original :func:`example` 566 would have been lost. 567 568 569.. _partial-objects: 570 571:class:`partial` Objects 572------------------------ 573 574:class:`partial` objects are callable objects created by :func:`partial`. They 575have three read-only attributes: 576 577 578.. attribute:: partial.func 579 580 A callable object or function. Calls to the :class:`partial` object will be 581 forwarded to :attr:`func` with new arguments and keywords. 582 583 584.. attribute:: partial.args 585 586 The leftmost positional arguments that will be prepended to the positional 587 arguments provided to a :class:`partial` object call. 588 589 590.. attribute:: partial.keywords 591 592 The keyword arguments that will be supplied when the :class:`partial` object is 593 called. 594 595:class:`partial` objects are like :class:`function` objects in that they are 596callable, weak referencable, and can have attributes. There are some important 597differences. For instance, the :attr:`~definition.__name__` and :attr:`__doc__` attributes 598are not created automatically. Also, :class:`partial` objects defined in 599classes behave like static methods and do not transform into bound methods 600during instance attribute look-up. 601