Least-recently-used cache decorator. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. If *typed* is True, arguments of different types will be cached separately. For example, f(decimal.Decimal("3.0")) and f(3.0) will be treated as
(maxsize=128, typed=False)
| 551 | return key |
| 552 | |
| 553 | def lru_cache(maxsize=128, typed=False): |
| 554 | """Least-recently-used cache decorator. |
| 555 | |
| 556 | If *maxsize* is set to None, the LRU features are disabled and the cache |
| 557 | can grow without bound. |
| 558 | |
| 559 | If *typed* is True, arguments of different types will be cached separately. |
| 560 | For example, f(decimal.Decimal("3.0")) and f(3.0) will be treated as |
| 561 | distinct calls with distinct results. Some types such as str and int may |
| 562 | be cached separately even when typed is false. |
| 563 | |
| 564 | Arguments to the cached function must be hashable. |
| 565 | |
| 566 | View the cache statistics named tuple (hits, misses, maxsize, currsize) |
| 567 | with f.cache_info(). Clear the cache and statistics with f.cache_clear(). |
| 568 | Access the underlying function with f.__wrapped__. |
| 569 | |
| 570 | See: https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU) |
| 571 | |
| 572 | """ |
| 573 | |
| 574 | # Users should only access the lru_cache through its public API: |
| 575 | # cache_info, cache_clear, and f.__wrapped__ |
| 576 | # The internals of the lru_cache are encapsulated for thread safety and |
| 577 | # to allow the implementation to change (including a possible C version). |
| 578 | |
| 579 | if isinstance(maxsize, int): |
| 580 | # Negative maxsize is treated as 0 |
| 581 | if maxsize < 0: |
| 582 | maxsize = 0 |
| 583 | elif callable(maxsize) and isinstance(typed, bool): |
| 584 | # The user_function was passed in directly via the maxsize argument |
| 585 | user_function, maxsize = maxsize, 128 |
| 586 | wrapper = _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo) |
| 587 | wrapper.cache_parameters = lambda : {'maxsize': maxsize, 'typed': typed} |
| 588 | return update_wrapper(wrapper, user_function) |
| 589 | elif maxsize is not None: |
| 590 | raise TypeError( |
| 591 | 'Expected first argument to be an integer, a callable, or None') |
| 592 | |
| 593 | def decorating_function(user_function): |
| 594 | wrapper = _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo) |
| 595 | wrapper.cache_parameters = lambda : {'maxsize': maxsize, 'typed': typed} |
| 596 | return update_wrapper(wrapper, user_function) |
| 597 | |
| 598 | return decorating_function |
| 599 | |
| 600 | def _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo): |
| 601 | # Constants shared by all lru cache instances: |
no test coverage detected