fastcfg.config package
Submodules
fastcfg.config.attributes module
This module provides the ConfigAttributes class, which manages configuration attributes and their associated values.
The ConfigAttributes class acts as a proxy for the Config class, allowing it to handle unique attribute management efficiently. By separating attribute storage and retrieval into its own class, the Config class remains clean and focused on its primary responsibilities.
- class fastcfg.config.attributes.ConfigAttributes(config: None)[source]
Bases:
AbstractConfigUnit
Manages the actual configuration attributes and their associated values, ensuring they are stored and retrieved correctly.
This class acts as a proxy for the Config class, allowing it to handle unique attribute management efficiently. By separating attribute storage and retrieval into its own class, the Config class remains clean and focused on its primary responsibilities.
- __attributes
A dictionary to store configuration attributes.
- Type:
dict[str, IConfigItem]
- add_or_update_attribute(name: str, value: Any) None [source]
Adds a new attribute or updates an existing attribute in the configuration.
If the attribute already exists and is a BuiltInConfigItem, its value is updated. If the attribute is a LiveConfigItem, it is replaced with a new value. If the attribute does not exist, it is added as a new attribute.
- Parameters:
name (str) – The name of the attribute.
value (Any) – The value of the attribute, which will be converted to an IConfigItem.
- get_attribute(name) AbstractConfigItem [source]
Retrieves an attribute by name.
- Parameters:
name (str) – The name of the attribute to retrieve.
- Returns:
The configuration item associated with the given name.
- Return type:
IConfigItem
- Raises:
AttributeError – If the attribute does not exist.
- get_attributes() dict[str, AbstractConfigItem] [source]
Returns all attributes.
- Returns:
A dictionary of all configuration attributes.
- Return type:
dict[str, IConfigItem]
fastcfg.config.interface module
This module defines the ConfigInterface class, which handles environment-specific configurations and provides additional methods and attributes that are not directly related to configuration values.
- Classes:
ConfigInterface: Manages configuration attributes and environment settings.
- class fastcfg.config.interface.ConfigInterface(config, config_attributes, **kwargs)[source]
Bases:
ValidatableMixin
,EventListenerMixin
,AbstractConfigUnit
Handles environment-specific configurations and provides additional public methods and attributes that are not directly related to configuration values, nor are meant to be overriden by config attributes. This separation allows the Config class to have public functions and variables without cluttering the main configuration logic.
- _config_attributes
The configuration attributes.
- Type:
- _current_env
The current environment.
- Type:
str
- get_environment()
Retrieves the current environment.
- value()
Property that gets the configuration attributes as a dictionary.
- property environment: str | None
Gets the current environment.
- Returns:
The current environment.
- property environments
Gets the environments.
- Returns:
The environments.
- import_values(file_path: str)[source]
Imports the current configuration values from a file using deep merge.
If an environment is currently active, the import will only affect that environment. If no environment is active, the import will affect the root configuration. Existing nested values are preserved unless explicitly overwritten.
- remove_environment() ConfigInterface [source]
Removes the current environment.
- set_environment(env: str | None) ConfigInterface [source]
Sets the current environment.
- Parameters:
env – The environment to set.
- Raises:
ValueError – If the environment is invalid.
- to_dict() dict [source]
Gets the configuration attributes as a dictionary. Fully serializable. It will also resolve nested Config objects to their dictionary representation and ConfigItems as their value.
- Returns:
The configuration attributes.
- Return type:
dict
- update(other=None, **kwargs) ConfigInterface [source]
Updates the configuration attributes using deep merge. Works like dict.update() but preserves nested values.
Can accept either a dict-like object or keyword arguments. If an environment is currently active, updates will only affect that environment. Dictionaries are automatically converted to Config objects.
- Parameters:
other – A dict-like object or iterable of key-value pairs.
**kwargs – Additional keyword arguments.
- property value
Gets the configuration attributes as a dictionary. Primarily used to get the value for validation.
- Returns:
The configuration attributes.
- Return type:
dict
fastcfg.config.items module
This module defines the configuration item classes for the fastcfg module. These are used as interfaces to interact with when accessing configuration attributes.
- Classes:
AbstractConfigItem: An abstract base class for configuration items, providing a common interface and shared functionality. BuiltInConfigItem: A concrete class representing configuration items that hold built-in data type values. LiveConfigItem: A concrete class representing configuration items that are dynamically calculated upon access.
Usage Examples:
```python # Creating a BuiltInConfigItem config.item = 42 # Automatically wraps the value in a BuiltInConfigItem print(config.item.value) # Output: 42 config.item.value = 100 print(config.item.value) # Output: 100
# Creating a LiveConfigItem with a state tracker class StateTracker:
- def get_state(self):
return “dynamic_value”
state_tracker = StateTracker() live_item = LiveConfigItem(state_tracker) print(live_item.value) # Output: “dynamic_value” ```
- class fastcfg.config.items.AbstractConfigItem[source]
Bases:
ValidatableMixin
,EventListenerMixin
,ABC
The AbstractConfigItem class serves as an abstract base class for configuration items in the fastcfg module.
- Purpose:
The primary purpose of the AbstractConfigItem class is to define a common interface and shared functionality for all configuration items.
It ensures that all configuration items can be validated and have a consistent way of getting and setting their values.
This class also provides mechanisms to handle nested dictionary values by wrapping them in ValueWrapper instances.
By using AbstractConfigItem as the base class for configuration attributes, the Config class can manage different types of configuration items uniformly.
The design choice to use AbstractConfigItem allows for flexibility and extensibility, enabling the creation of custom configuration items (e.g., BuiltInConfigItem, LiveConfigItem) that can have specialized behavior.
The ValueWrapper class leverages AbstractConfigItem to provide seamless interaction with both the underlying value and the configuration item’s methods, ensuring that validation and other functionalities are consistently applied.
- Features:
Validation: Inherits from ValidatableMixin to provide validation capabilities.
Abstract Methods: Defines abstract methods _get_value and _set_value that must be implemented by subclasses.
Value Handling: Provides a value property to get and set the configuration item’s value, with special handling for dictionary values.
Dynamic Attribute Access: Implements __getattr__ to suppress type hint errors and handle dynamic attribute access.
- _wrapped_dict_items
A dictionary to store wrapped dictionary items.
- Type:
Dict[str, AbstractConfigItem]
- value()
Property to get and set the configuration item’s value.
- property value: Any
Gets the value of the configuration item.
This property retrieves the value of the configuration item by calling the _get_value method. If the value is a dictionary, it wraps the dictionary items in ValueWrapper instances to ensure consistent interaction with both the underlying value and the configuration item’s methods.
The value is implemented as a property instead of a direct attribute to provide controlled access and allow for additional processing (such as wrapping dictionary values) when the value is retrieved.
- Returns:
The value of the configuration item. If the value is a dictionary, the dictionary items are wrapped in ValueWrapper instances.
- Return type:
Any
- class fastcfg.config.items.BuiltInConfigItem(value: Any)[source]
Bases:
AbstractConfigItem
The BuiltInConfigItem class represents a configuration item that holds a built-in data type value.
- Purpose:
This concrete class is used to wrap built-in data types (e.g., int, float, str) as configuration items.
It provides implementations for the abstract methods _get_value and _set_value defined in AbstractConfigItem.
It’s used for static data types which don’t change unless the attribute itself is directly modified.
- _value
The underlying value of the configuration item.
- Type:
Any
- __init__(value
Any): Initializes the BuiltInConfigItem with the given value.
- _set_value(new_value
Any): Sets the underlying value of the configuration item.
- class fastcfg.config.items.LiveConfigItem(state_tracker)[source]
Bases:
AbstractConfigItem
The LiveConfigItem class represents a configuration item that is dynamically calculated upon access.
- Purpose:
This class is used for configuration items that need to be dynamically validated based on an external state.
It provides implementations for the abstract methods _get_value and _set_value defined in AbstractConfigItem.
Unlike BuiltInConfigItem, it does not allow direct setting of its value.
- _state_tracker
An external state tracker that provides the current state for the configuration item.
- Type:
StateTracker
- _set_value(new_value
Any): Raises an exception as direct setting of value is not allowed.
- value()
Property to get the current state and trigger validation.
- as_callable()[source]
Returns a callable that always returns the current state of the configuration item.
- Returns:
A callable that always returns the current state of the configuration item.
- Return type:
Callable
- property value: Any
Gets the current state of the configuration item and triggers validation.
This property retrieves the current state from the state tracker by calling the _get_value method. It also triggers validation to ensure the state is valid.
- Returns:
The current state of the configuration item.
- Return type:
Any
fastcfg.config.state module
- class fastcfg.config.state.AbstractLiveStateTracker(retry: bool = False, use_cache: bool = False, backoff_policy: BackoffPolicy | None = None, cache: Cache | None = None)[source]
Bases:
AbstractStateTracker
,RetriableMixin
,CacheMixin
,ABC
Base class for state trackers with optional retry and caching. This class provides the basis for all StateTrackers that are dynamically fetched on attribute access from a Config instance.
- Purpose:
This class combines state tracking, retry logic, and caching capabilities.
It provides a unified interface for fetching state with support for retries and caching.
- _cache_uuid_key
The cache key for the state.
- Type:
str
- class fastcfg.config.state.AbstractStateTracker[source]
Bases:
ABC
Abstract base class for a state tracker which is used to fetch the current state for LiveConfigItems.
- Purpose:
This class defines a common interface for state trackers.
It ensures that all state trackers can fetch the current state through a consistent method.
- implemented by subclasses.
- class fastcfg.config.state.CacheMixin(use_cache: bool = False, cache: Cache | None = None)[source]
Bases:
object
Mixin providing caching logic.
- class fastcfg.config.state.RetriableMixin(retry: bool = False, backoff_policy: BackoffPolicy = None)[source]
Bases:
object
Mixin providing retry logic.
- Purpose:
This mixin adds retry capabilities to state tracker classes that need to handle transient failures.
It uses an exponential backoff strategy to retry operations.
- _retry
Whether to enable retry logic.
- Type:
bool
- _backoff_policy
The backoff policy to use.
- Type:
fastcfg.config.utils module
- fastcfg.config.utils.create_config_dict(item: dict) None [source]
Converts a dictionary (including a ValueWrapped dictionary) into a Config object. This is abstracted into this module as it’s used in multiple places.
- Parameters:
item (dict) – The dictionary to be converted.
- Returns:
A Config object initialized with the dictionary’s key-value pairs.
- Return type:
Config
- fastcfg.config.utils.deep_merge_config(target, updates)[source]
Recursively merge updates into target, preserving existing nested values.
This function performs a deep merge where: - Existing nested Config objects are recursively updated - New keys are added - Existing non-Config values are replaced - Dictionaries are automatically converted to Config objects
- Parameters:
target – The target Config object to update
updates – Dictionary of updates to apply
- fastcfg.config.utils.potentially_has_children(obj: Any) bool [source]
Checks if the given object is potentially has children. Currently dict and Config instances are considered to have children.
- Parameters:
obj (Any) – The object to check.
- Returns:
True if the object type is in POTENTIALLY_HAS_CHILDREN, False otherwise.
- Return type:
bool
- fastcfg.config.utils.resolve_all_values(obj: dict | None) dict [source]
Recursively resolves all values in a dictionary or Config object.
This function traverses the given object, resolving any nested dictionaries or Config objects, and extracting the values of IConfigItem instances.
- Parameters:
obj (Union[dict, Config]) – The object to resolve.
- Returns:
A dictionary with all values resolved.
- Return type:
dict
- Raises:
ValueError – If the object is not a dictionary or Config object.
fastcfg.config.value_wrapper module
- class fastcfg.config.value_wrapper.OperatorsMixin[source]
Bases:
object
Mixin class that provides operator overloading for ValueWrapper.
This class implements all the magic methods needed to make a wrapped value behave like its underlying value in various operations by using Python’s operator module for proper delegation.
- class fastcfg.config.value_wrapper.ValueWrapper(item: None)[source]
Bases:
OperatorsMixin
A wrapper class that allows treating an instance of AbstractConfigItem as equivalent to its underlying value. This class delegates attribute access to the underlying value or the item itself, enabling seamless interaction with both the value and the AbstractConfigItem’s methods.
This is useful for scenarios where you want to work directly with the value of a configuration item while still being able to access and utilize the methods of the AbstractConfigItem, such as add_validator.
Example
config = Config() config.my_number = 42 # Automatically wraps built-in types with a BuiltInConfigItem
# Accessing the value directly print(config.my_number) # Output: 42
print(config.my_number + config.my_number) # Output 84
# Using AbstractConfigItem methods config.my_number.add_validator(RangeValidator(1, 50))
- static factory(obj) ValueWrapper [source]
Module contents
This module initializes the fastcfg.config package, making the Config class available for importing.
The Config class is designed to manage configuration settings in a structured and flexible manner, supporting dynamic attribute management, nested configurations, validation, and environment-specific configurations.
Usage Example:
`python from fastcfg.config import Config # Initialize a Config object with some settings config = Config(database={'host': 'localhost', 'port': 5432}) # Access configuration values print(config.database.host) # Output: localhost # Add new configuration attributes config.new_attr = 'value' print(config.new_attr) # Output: value `