Behavioral Decorators¶
Retry logic and thread synchronization.
Retryable
¶
A decorator that retries a function call a specified number of times if it raises an exception or if the request status code is not 200.
This decorator catches JSONDecodeError, specific requests exceptions, botocore exceptions, and general Exception during the function execution,
retries the function up to max_retries times, and logs warnings and errors based on verbosity. If the maximum number of retries is reached,
it raises the last caught exception.
| RETURNS | DESCRIPTION |
|---|---|
|
The result of the decorated function, if it succeeds within the allowed retries. |
Synchronized
¶
Decorator to ensure that a method is executed with a lock, preventing concurrent access from multiple threads.
This decorator is useful in scenarios where thread safety is a concern, particularly when accessing shared resources such as database connections, files, or any other critical section of the code that should not be concurrently accessed.
The synchronized decorator can be applied to any method that requires thread-safe execution. It uses a threading
lock to ensure that only one thread can execute the decorated method at any given time.
| RETURNS | DESCRIPTION |
|---|---|
Callable[[Callable[..., Any]], Callable[..., Any]] **Example Usage**:: >>> import threading >>> from mypackage.decorators import synchronized >>> >>> class SharedResource: >>> _lock = threading.Lock() >>> >>> @synchronized(_lock) >>> def critical_section(self, value): >>> # critical section that should not be accessed concurrently >>> print(f"Processing value: {value}") >>> >>> resource = SharedResource() >>> >>> # Simulating concurrent access to the critical section >>> t1 = threading.Thread(target=resource.critical_section, args=(1,)) >>> t2 = threading.Thread(target=resource.critical_section, args=(2,)) >>> t1.start() >>> t2.start() >>> t1.join() >>> t2.join()
|
A decorator that wraps the target method with lock acquisition and release. |