comparison env/lib/python3.9/site-packages/humanfriendly/decorators.py @ 0:4f3585e2f14b draft default tip

"planemo upload commit 60cee0fc7c0cda8592644e1aad72851dec82c959"
author shellac
date Mon, 22 Mar 2021 18:12:50 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4f3585e2f14b
1 # Human friendly input/output in Python.
2 #
3 # Author: Peter Odding <peter@peterodding.com>
4 # Last Change: March 2, 2020
5 # URL: https://humanfriendly.readthedocs.io
6
7 """Simple function decorators to make Python programming easier."""
8
9 # Standard library modules.
10 import functools
11
12 # Public identifiers that require documentation.
13 __all__ = ('RESULTS_ATTRIBUTE', 'cached')
14
15 RESULTS_ATTRIBUTE = 'cached_results'
16 """The name of the property used to cache the return values of functions (a string)."""
17
18
19 def cached(function):
20 """
21 Rudimentary caching decorator for functions.
22
23 :param function: The function whose return value should be cached.
24 :returns: The decorated function.
25
26 The given function will only be called once, the first time the wrapper
27 function is called. The return value is cached by the wrapper function as
28 an attribute of the given function and returned on each subsequent call.
29
30 .. note:: Currently no function arguments are supported because only a
31 single return value can be cached. Accepting any function
32 arguments at all would imply that the cache is parametrized on
33 function arguments, which is not currently the case.
34 """
35 @functools.wraps(function)
36 def wrapper():
37 try:
38 return getattr(wrapper, RESULTS_ATTRIBUTE)
39 except AttributeError:
40 result = function()
41 setattr(wrapper, RESULTS_ATTRIBUTE, result)
42 return result
43 return wrapper