Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions configurize/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,7 @@ def __init__(self, **kwargs):
)
self._merge_args(kwargs)

# Handle assigned Config subclasses (e.g., sub = SubConfig)
for k, v in self.items(deref=False):
if type(v) is type and issubclass(v, Config):
v = v()
Expand All @@ -319,6 +320,26 @@ def __init__(self, **kwargs):
v._father = weakref.ref(self)
v._sub_cfg_name = k

# Handle type-annotated Config subclasses (e.g., sub: SubConfig)
annotations = self._get_class_annotations()
for k, annotation_type in annotations.items():
# Skip if already set as an attribute
if hasattr(self, k):
continue
# Check if the annotation is a Config subclass type
try:
if type(annotation_type) is type and issubclass(
annotation_type, Config
):
# Instantiate the Config subclass
v = annotation_type()
setattr(self, k, v)
v._father = weakref.ref(self)
v._sub_cfg_name = k
except TypeError:
# issubclass raises TypeError if annotation_type is not a class
pass

if self._allow_search:
self._flatten_args = self._flatten_config()

Expand Down
28 changes: 18 additions & 10 deletions tests/test_config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Basic tests for configurize.Config"""

from __future__ import annotations

from configurize import Config
from configurize.reference import Ref

Expand Down Expand Up @@ -29,25 +31,31 @@ class BaseConfig(Config):
assert cfg.b == 2


def test_config_references():
"""Test using Ref to reference other config values"""
class SubConfig(Config):
value = 100
self_ref = Ref(".value")
parent_ref = Ref("..base_value")


class SubConfig(Config):
value = 100
self_ref = Ref(".value")
parent_ref = Ref("..base_value")
class ParentConfig(Config):
base_value = 42
optional: int | None
sub = SubConfig
sub2: SubConfig

class ParentConfig(Config):
base_value = 42
optional: int | None
sub = SubConfig

def test_config_references():
"""Test using Ref to reference other config values"""

cfg = ParentConfig()
cfg.sanity_check()
# Test self-reference
assert cfg.sub.self_ref == 100
assert cfg.sub2.self_ref == 100
# Test parent reference
assert cfg.sub.parent_ref == 42
assert cfg.sub2.parent_ref == 42
# Verify references update when source changes
cfg.base_value = 99
assert cfg.sub.parent_ref == 99
assert cfg.sub2.parent_ref == 99