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