-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
27 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,30 +1,43 @@ | ||
class ExtendedConfig: | ||
from pydantic import BaseModel | ||
|
||
|
||
class ExtendedConfig(BaseModel): | ||
"""Configuration for extended functionalities. | ||
Attributes: | ||
Values depend on the defined section | ||
""" | ||
|
||
extended: dict = {} | ||
# No explicit fields are defined; extra keys will be allowed via the model configuration. | ||
|
||
class Config: | ||
extra = 'allow' # allow arbitrary extra fields | ||
|
||
def __str__(self): | ||
def __str__(self) -> str: | ||
# Build string representation using all model attributes | ||
attr_str = [] | ||
for attr_name, attr_value in self.extended.items(): | ||
# __dict__ contains both declared and extra attributes | ||
for attr_name, attr_value in self.__dict__.items(): | ||
attr_str.append(f'{attr_name}={repr(attr_value)}') | ||
return f"ExtendedConfig({', '.join(attr_str)})" | ||
|
||
@classmethod | ||
def from_dict(cls, extended_config_dict: dict) -> 'ExtendedConfig': | ||
return cls(extended_config_dict) | ||
# Create an instance using Pydantic V2's model validation | ||
return cls.model_validate(extended_config_dict) | ||
|
||
def __init__(self, dict=None): | ||
self.extended = dict | ||
|
||
def __repr__(self): | ||
def __repr__(self) -> str: | ||
return self.__str__() | ||
|
||
def __getitem__(self, key): | ||
return self.extended[key] | ||
|
||
def __getattr__(self, key): | ||
return self.extended[key] | ||
def __getitem__(self, key: str) -> object: | ||
# Allow dictionary-like access to attributes | ||
return self.__dict__[key] | ||
|
||
def __getattr__(self, key: str) -> object: | ||
# Fallback for attribute access if the attribute is not found normally | ||
try: | ||
return self.__dict__[key] | ||
except KeyError as e: | ||
raise AttributeError( | ||
f"'ExtendedConfig' object has no attribute '{key}'" | ||
) from e |