power_decos package
Submodules
power_decos.cache_decorator module
cache_module
This module provides a simple caching mechanism for function results. It includes a Cache class that can be used to cache and retrieve function results, improving performance for expensive or frequently called functions.
- cls Cache:
clear_cache(): Clears the cache, resetting it to an empty state.
manual_cache(func_name: callable, return_value: any, *args, **kwargs): Manually adds a result to the cache.
cache(func: callable): Decorator that caches the result of a function call.
get_cached_value(func_name: callable, compare_all: bool = True, *args, **kwargs): Retrieve cached results based on function name and optionally arguments.
- Usage:
Instantiate the Cache class and decorate functions with the @cache decorator to enable caching.
- class power_decos.cache_decorator.Cache[source]
Bases:
objectA simple caching mechanism for storing and retrieving function results.
This class provides a way to cache the results of function calls, improving performance for expensive or frequently called functions.
- Variables:
cache – Saved output to tuple(func.__name, args, frozenset(kwargs.item()))
- cache_func(func: callable) callable[source]
Decorator to cache the result of a function call.
If the function is called with the same arguments, the cached result will be returned instead of calling the function again.
- Parameters:
func – The function to be cached.
- Returns:
The wrapper function that handles caching.
- clear_cache()[source]
Clear the cache.
Resets the cache to an empty state, removing all stored results.
- get_cached_value(func_name: callable, compare_all: bool, *args, **kwargs) any[source]
Retrieve cached results based on function name and optionally arguments.
This method returns cached values for a function based on the specified func_name, args, and kwargs. It can either look for an exact match or allow for partial matches depending on the compare_all flag.
- Parameters:
func_name – The name of the function whose result is being retrieved.
compare_all – If True, requires an exact match of func_name, args, and kwargs. If False, allows partial matches where args and/or kwargs can be omitted.
args – Positional arguments used to generate the cache key. If provided, they are used for partial matching when compare_all is False.
kwargs – Keyword arguments used to generate the cache key. If provided, they are used for partial matching when compare_all is False.
Returns:
A single cached result if compare_all is True and an exact match is found.
A list of cached results if compare_all is False and partial matches are found.
None if no match is found.
- manual_cache(func_name: callable, return_value: any, *args, **kwargs)[source]
Manually add a result to the cache.
- Parameters:
func_name – The name of the function whose result is being cached.
return_value – The result to cache.
args – Positional arguments used to generate the cache key.
kwargs – Keyword arguments used to generate the cache key.
power_decos.log_decorator module
A logging management module that defines the following class:
LoggerManager: Handles all logging functionality with configurable settings and utility methods.
Classes
LoggerManager: Manages the logging system with configurable settings, including terminal and file logging, JSON or text formatting, and rotating log files.
How To Use This Module
Import it:
import logging_managerorfrom logging_manager import LoggerManager.Create an instance of LoggerManager:
logger = LoggerManager()
Initialize the logger, specifying options such as logging to terminal, file, and format (JSON or text):
logger.init_logger(log_in_terminal=True, log_in_file=True)
Log messages at various levels (INFO, DEBUG, etc.):
logger.log_info(“This is an informational message”)
Use log_func as a decorator to automatically log function entry, exit, and exceptions:
@logger.log_func def my_function():
# function code
Customize the logging configuration by adding/removing handlers or adjusting log format as needed.
- Clean up resources explicitly if needed using the __del__ method which is automatically called when the instance is about to be destroyed.
This should be used when needing to access the log json files
- class power_decos.log_decorator.LoggerManager[source]
Bases:
object- init_logger(log_in_terminal: bool = False, log_in_file: bool = True, logfile_name: str = None, log_file_in_json: bool = True, use_rotating_file_handler: bool = False, max_bytes: int = 1048576, backup_counts: int = 3, custom_logfile_formatter=None)[source]
Initializes the logging system by setting up handlers for logging to the terminal and/or a file. Supports JSON and text log formats, as well as rotating file handlers.
Note: The log file (e.g., .jsonl) cannot be accessed or modified while a handler is actively using it. Ensure to release file handlers before accessing the log file. This can be done in two ways:
del instance
instance(log_in_file = False)
- Parameters:
log_in_terminal – If True, logs messages to the terminal.
log_in_file – If True, logs messages to a file.
logfile_name – The name of the log file. If None, defaults to a name based on the current date.
log_file_in_json – If True, formats log messages as JSON lines in the log file.
use_rotating_file_handler – If True, uses a rotating file handler.
max_bytes – The maximum size (in bytes) of the log file before it is rotated.
backup_counts – The number of backup files to keep before deleting the oldest.
custom_logfile_formatter – A custom formatter for the log file. Defaults to JSONLineFormatter or a text formatter.
- log_func(skip_exception: bool = False, log_info: str = None) callable[source]
Decorator to log function executions and exceptions.
- Parameters:
skip_exception – If True, exceptions are logged but not raised. DEFAULT: False
log_info – Additional information to log. DEFAULT: Doesn’t log extra information
- Returns:
The decorated function.
power_decos.retry_decorator module
A module containing the retry decorator for handling function retries on exceptions.
Decorators
retry: Re-executes a function upon encountering specific exceptions, with a configurable number of retries and delay between attempts.
Functions
retry: The main decorator function that enables retry functionality.
retries: Number of retry attempts (default is 3).
delay: Delay in seconds between retry attempts (default is 1).
raise_exception: Whether to raise the exception after the final retry (default is False).
exception_types: The exception(s) that should trigger a retry. Can be a single type or a tuple of types.
Exception classes
This module does not define any specific exception classes.
How To Use This Module
Import it:
import retry_decoratororfrom retry_decorator import retry.Use the retry decorator to add retry functionality to a function:
@retry(retries=3, delay=2, raise_exception=True) def my_function():
# function code that may raise an exception pass
Customize the retry behavior by adjusting the keyword arguments retries, delay, raise_exception, and exception_types as needed.
Example
```python from retry_decorator import retry
@retry(retries=5, delay=1, raise_exception=True) def unreliable_function():
# Code that may fail and trigger retries pass
unreliable_function()
- power_decos.retry_decorator.retry(retries: int = 3, delay: float = 1, raise_exception: bool = False, exception_types: BaseException | tuple[BaseException] = <class 'Exception'>) callable[source]
Reexecutes a function upon encountering an exception.
- Parameters:
retries (int) – Number of times the function should retry upon encountering an exception.
delay (float) – Time in seconds to wait between retry attempts.
raise_exception (bool) – Whether to raise the exception after exhausting all retries.
exception_types – Exception types that should trigger a retry. Can be a single type or a tuple of types.
- Raises:
ValueError – If retries is less than 1 or delay is less than or equal to 0.
TypeError – If exception_types is not a type or a tuple of types.
power_decos.run_time_decorator module
A module containing the get_time decorator for measuring and logging the execution time of functions.
Decorators
get_time: Measures the execution time of a function and logs the duration.
Functions
get_time: The main decorator that calculates the time a function takes to execute.
It prints and logs the time taken by the decorated function.
The execution time is logged regardless of whether the function raises an exception or not.
Exception classes
This module does not define any specific exception classes.
How To Use This Module
Import it:
import time_decoratororfrom time_decorator import get_time.Use the get_time decorator to measure the execution time of a function:
@get_time def my_function():
# function code pass
The execution time will be logged with a message indicating how long the function took.
Example
```python from time_decorator import get_time
@get_time def slow_function():
# Code that takes time to run pass
slow_function()
- power_decos.run_time_decorator.get_time(func: callable) callable[source]
Wrapps Function and returns execution time
Prints: - run_time (float): -> the time of the execution of a Function
- Returns:
Callable[…, Any]: The decorated function that prints its execution time.
- Note:
This decorator will print the execution time regardless of whether the function raises an exception or not.
Module contents
Package full of utility decorators
Decorators:
retry(num_of_retries=3, interval=1): Retries a function upon failure for a specified number of times, with a delay between attempts.
get_time(): Measures and prints the execution time of the decorated function.
- log_decorator (cls LogManager):
log_init(): Initializes and configures how logging data should be handled (e.g., terminal, file, JSON).
log_func(): Logs the entry, exit, and any exceptions of a function to .jsonl or .log files.
log_info(message: str): Logs custom informational messages to .jsonl or .log files.
- cache_decorator (cls Cache):
clear_cache(): Clears the cache, resetting it to an empty state.
manual_cache(func_name: callable, return_value: any, *args, **kwargs): Manually adds a result to the cache.
cache(func: callable): Decorator that caches the result of a function call.
get_cached_value(func_name: callable, compare_all: bool = True, *args, **kwargs) : Retrieve cached results based on function name and optionally arguments.
This module provides easy-to-use decorators for common tasks like retrying failed operations, measuring execution time, structured logging, and result caching.
Params: - __version__: The version of the package. - __author__: The author of the package.
- class power_decos.Cache[source]
Bases:
objectA simple caching mechanism for storing and retrieving function results.
This class provides a way to cache the results of function calls, improving performance for expensive or frequently called functions.
- Variables:
cache – Saved output to tuple(func.__name, args, frozenset(kwargs.item()))
- cache_func(func: callable) callable[source]
Decorator to cache the result of a function call.
If the function is called with the same arguments, the cached result will be returned instead of calling the function again.
- Parameters:
func – The function to be cached.
- Returns:
The wrapper function that handles caching.
- clear_cache()[source]
Clear the cache.
Resets the cache to an empty state, removing all stored results.
- get_cached_value(func_name: callable, compare_all: bool, *args, **kwargs) any[source]
Retrieve cached results based on function name and optionally arguments.
This method returns cached values for a function based on the specified func_name, args, and kwargs. It can either look for an exact match or allow for partial matches depending on the compare_all flag.
- Parameters:
func_name – The name of the function whose result is being retrieved.
compare_all – If True, requires an exact match of func_name, args, and kwargs. If False, allows partial matches where args and/or kwargs can be omitted.
args – Positional arguments used to generate the cache key. If provided, they are used for partial matching when compare_all is False.
kwargs – Keyword arguments used to generate the cache key. If provided, they are used for partial matching when compare_all is False.
Returns:
A single cached result if compare_all is True and an exact match is found.
A list of cached results if compare_all is False and partial matches are found.
None if no match is found.
- manual_cache(func_name: callable, return_value: any, *args, **kwargs)[source]
Manually add a result to the cache.
- Parameters:
func_name – The name of the function whose result is being cached.
return_value – The result to cache.
args – Positional arguments used to generate the cache key.
kwargs – Keyword arguments used to generate the cache key.
- class power_decos.LoggerManager[source]
Bases:
object- init_logger(log_in_terminal: bool = False, log_in_file: bool = True, logfile_name: str = None, log_file_in_json: bool = True, use_rotating_file_handler: bool = False, max_bytes: int = 1048576, backup_counts: int = 3, custom_logfile_formatter=None)[source]
Initializes the logging system by setting up handlers for logging to the terminal and/or a file. Supports JSON and text log formats, as well as rotating file handlers.
Note: The log file (e.g., .jsonl) cannot be accessed or modified while a handler is actively using it. Ensure to release file handlers before accessing the log file. This can be done in two ways:
del instance
instance(log_in_file = False)
- Parameters:
log_in_terminal – If True, logs messages to the terminal.
log_in_file – If True, logs messages to a file.
logfile_name – The name of the log file. If None, defaults to a name based on the current date.
log_file_in_json – If True, formats log messages as JSON lines in the log file.
use_rotating_file_handler – If True, uses a rotating file handler.
max_bytes – The maximum size (in bytes) of the log file before it is rotated.
backup_counts – The number of backup files to keep before deleting the oldest.
custom_logfile_formatter – A custom formatter for the log file. Defaults to JSONLineFormatter or a text formatter.
- log_func(skip_exception: bool = False, log_info: str = None) callable[source]
Decorator to log function executions and exceptions.
- Parameters:
skip_exception – If True, exceptions are logged but not raised. DEFAULT: False
log_info – Additional information to log. DEFAULT: Doesn’t log extra information
- Returns:
The decorated function.
- power_decos.get_time(func: callable) callable[source]
Wrapps Function and returns execution time
Prints: - run_time (float): -> the time of the execution of a Function
- Returns:
Callable[…, Any]: The decorated function that prints its execution time.
- Note:
This decorator will print the execution time regardless of whether the function raises an exception or not.
- power_decos.retry(retries: int = 3, delay: float = 1, raise_exception: bool = False, exception_types: BaseException | tuple[BaseException] = <class 'Exception'>) callable[source]
Reexecutes a function upon encountering an exception.
- Parameters:
retries (int) – Number of times the function should retry upon encountering an exception.
delay (float) – Time in seconds to wait between retry attempts.
raise_exception (bool) – Whether to raise the exception after exhausting all retries.
exception_types – Exception types that should trigger a retry. Can be a single type or a tuple of types.
- Raises:
ValueError – If retries is less than 1 or delay is less than or equal to 0.
TypeError – If exception_types is not a type or a tuple of types.