Skip to content

Commit

Permalink
fix(BaseConfig): add subconfig initialization
Browse files Browse the repository at this point in the history
This commit refactors the `BaseConfig` class by adding a new method `initialize_subconfigs` that initializes subconfigs with the given config data. The method updates the object's dictionary with the provided config data, after excluding any attributes specified in the object's `exclude` list. This ensures that subconfigs are properly initialized and can be accessed within the `BaseConfig` class.
  • Loading branch information
entelecheia committed Jul 4, 2023
1 parent 15b583f commit 6e84c4e
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion src/hyfi/composer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -783,6 +783,7 @@ class BaseConfig(BaseModel):
_init_args_: Dict[str, Any] = {}
_exclude_: Set[str] = set()
_property_set_methods_: Dict[str, str] = {}
_subconfigs_: Dict[str, Any] = {}

model_config = ConfigDict(
arbitrary_types_allowed=True,
Expand All @@ -793,6 +794,7 @@ class BaseConfig(BaseModel):
def __init__(self, **config_kwargs):
logger.debug("init %s with %s", self.__class__.__name__, config_kwargs)
super().__init__(**config_kwargs)
self.initialize_subconfigs(config_kwargs)

def __setattr__(self, key, val):
"""
Expand All @@ -813,7 +815,7 @@ def __setattr__(self, key, val):

@model_validator(mode="before")
def validate_model_config_before(cls, data):
logger.debug("validate_model_config_before: %s", data)
# logger.debug("Validating model config before validating each field.")
_config_name_ = data.get("_config_name_", getattr(cls._config_name_, "default", "__init__")) # type: ignore
_config_group_ = data.get("_config_group_", getattr(cls._config_group_, "default")) # type: ignore
_class_name_ = cls.__name__ # type: ignore
Expand All @@ -838,6 +840,25 @@ def validate_model_config_before(cls, data):
# logger.debug("validate_model_config_after")
# return model

def initialize_subconfigs(self, config_kwargs):
"""
Initializes subconfigs with the given config data.
The function updates the object's dictionary with the given config data,
after excluding any attributes specified in the object's `exclude` list.
Args:
**config_kwargs: The config data to update the object with.
Returns:
None
"""
self._subconfigs_ = self._subconfigs_ or {}
for name, config in self._subconfigs_.items():
if name in config_kwargs and isinstance(config_kwargs[name], dict):
cfg = config_kwargs[name]
logger.debug("Initializing subconfig %s with %s", name, cfg)
setattr(self, name, config.model_validate(cfg))

def export_config(
self,
exclude: Optional[Union[str, List[str], Set[str], None]] = None,
Expand Down

0 comments on commit 6e84c4e

Please sign in to comment.