Decorators¶
The decorate module provides a collection of useful decorators for adding functionality to your functions, such as timing, memoization, and retries.
memoize(func)
¶
Caches the results of a function to avoid redundant computations.
This decorator uses a Least Recently Used (LRU) cache to store the results of function calls with specific arguments. If the same arguments are provided again, the cached result is returned immediately without re-executing the function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
The function to be decorated. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[Any], Any]
|
Callable[[Any], Any]: The wrapped function with memoization. |
Example
Cache a computationally expensive function:
@memoize
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
# First call computes and caches the result
start_time = time.time()
result1 = fibonacci(30)
duration1 = time.time() - start_time
print(f"Result: {result1}, Time: {duration1:.4f}s")
# Second call returns the cached result instantly
start_time = time.time()
result2 = fibonacci(30)
duration2 = time.time() - start_time
print(f"Result: {result2}, Time: {duration2:.4f}s")
Source code in opencrate/core/utils/decorate.py
rate_limit(calls, period)
¶
Limits the number of times a function can be called within a time period.
This decorator restricts the execution frequency of a function. If the number of calls exceeds the specified limit within the given period, it raises an exception.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
calls
|
int
|
Maximum number of allowed calls within the time period. |
required |
period
|
float
|
The time period in seconds. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[Any], Any]
|
Callable[[Any], Any]: The wrapped function with rate-limiting. |
Raises:
| Type | Description |
|---|---|
Exception
|
If the rate limit is exceeded. |
Example
Limit a function to 2 calls every 5 seconds:
@rate_limit(calls=2, period=5)
def limited_function():
print("Function called.")
# First two calls succeed
limited_function()
limited_function()
# Third call fails
try:
limited_function()
except Exception as e:
print(e)
# Wait for the period to reset
time.sleep(5)
print("Waited 5 seconds...")
# Call succeeds again
limited_function()
Source code in opencrate/core/utils/decorate.py
retry(max_retries=3, delay=2.0, exceptions=None)
¶
Retries a function call a specified number of times on failure.
This decorator automatically re-executes a function if it raises an exception. It can be configured to retry a specific number of times, with a delay between attempts, and for specific exception types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_retries
|
int
|
Maximum number of retry attempts. Defaults to 3. |
3
|
delay
|
float
|
Delay between retries in seconds. Defaults to 2.0. |
2.0
|
exceptions
|
Exception or tuple of Exception
|
An exception or tuple of exceptions to catch. If |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[Any], Any]
|
Callable[[Any], Any]: The wrapped function with retry functionality. |
Raises:
| Type | Description |
|---|---|
Exception
|
If the function fails after all retry attempts. |
Example
Successful execution after a few retries:
import random
@retry(max_retries=5, delay=1)
def flaky_api_call():
print("Attempting to call API...")
if random.random() > 0.7:
return "Success!"
raise ConnectionError("Failed to connect")
flaky_api_call()
Attempting to call API...
Retrying flaky_api_call()... (1/5)
Attempting to call API...
Retrying flaky_api_call()... (2/5)
Attempting to call API...
Success!
Failure after all retries:
@retry(max_retries=3, delay=0.5)
def always_fail():
print("Executing and failing...")
raise ValueError("Permanent error")
try:
always_fail()
except Exception as e:
print(e)
Executing and failing...
Retrying always_fail()... (1/3)
Executing and failing...
Retrying always_fail()... (2/3)
Executing and failing...
always_fail() failed after 3 retries:
Permanent error
Retry only for specific exceptions:
Output:Source code in opencrate/core/utils/decorate.py
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | |
timeit(record=False)
¶
Measures and logs the execution time of a function.
This decorator prints the execution time of the decorated function each time it is
called. If record is set to True, it also records each execution time and
provides a summarize() method to display summary statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
Callable[[Any], Any]
|
Callable[[Any], Any]: The wrapped function with timing capabilities. |
Example
Basic usage to time a function call:
Output:Record and summarize execution times:
@timeit(record=True)
def fast_function():
time.sleep(0.1)
for _ in range(5):
fast_function()
fast_function.summarize()
fast_function() executed in 100.23 ms
fast_function() executed in 100.11 ms
fast_function() executed in 100.35 ms
fast_function() executed in 100.18 ms
fast_function() executed in 100.09 ms
Total executions : 5
Mean time taken : 100.19 ms
Median time taken : 100.18 ms
Min time taken : 100.09 ms
Max time taken : 100.35 ms
Std deviation : 0.09 ms
Total time taken : 500.96 ms
Attempting to summarize without recording:
Output:Source code in opencrate/core/utils/decorate.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | |