Skip to content

Commit 73e5039

Browse files
author
Oleh Prypin
committed
Make it possible to create a subclass of SubConfig[T]
`SubConfig[SomeType]()` is now the preferred way to express `SubConfig(SomeType)` but more importantly, it is now possible to subclass `SubConfig[SomeType]` for post-processing of the value.
1 parent 8315da2 commit 73e5039

1 file changed

Lines changed: 20 additions & 13 deletions

File tree

mkdocs/config/config_options.py

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@ class SubConfig(Generic[SomeConfig], BaseConfigOption[SomeConfig]):
5656
enable validation with `validate=True`.
5757
"""
5858

59+
config_class: Callable[[], SomeConfig]
60+
5961
@overload
6062
def __init__(
6163
self: SubConfig[SomeConfig], config_class: type[SomeConfig], *, validate: bool = True
@@ -73,22 +75,27 @@ def __init__(
7375
def __init__(self, *config_options, validate=None):
7476
super().__init__()
7577
self.default = {}
76-
if (
77-
len(config_options) == 1
78-
and isinstance(config_options[0], type)
79-
and issubclass(config_options[0], Config)
80-
):
81-
if validate is None:
82-
validate = True
83-
(self._make_config,) = config_options
84-
else:
85-
self._make_config = functools.partial(LegacyConfig, config_options)
86-
self._do_validation = bool(validate)
78+
self._do_validation = True if validate is None else validate
79+
if type(self) is SubConfig:
80+
if (
81+
len(config_options) == 1
82+
and isinstance(config_options[0], type)
83+
and issubclass(config_options[0], Config)
84+
):
85+
(self.config_class,) = config_options
86+
else:
87+
self.config_class = functools.partial(LegacyConfig, config_options)
88+
self._do_validation = False if validate is None else validate
89+
90+
def __class_getitem__(cls, config_class: type[Config]):
91+
"""Eliminates the need to write `config_class = FooConfig` when subclassing SubConfig[FooConfig]"""
92+
name = f'{cls.__name__}[{config_class.__name__}]'
93+
return type(name, (cls,), dict(config_class=config_class))
8794

8895
def run_validation(self, value: object) -> SomeConfig:
89-
config = self._make_config()
96+
config = self.config_class()
9097
try:
91-
config.load_dict(value)
98+
config.load_dict(value) # type: ignore
9299
failed, warnings = config.validate()
93100
except ConfigurationError as e:
94101
raise ValidationError(str(e))

0 commit comments

Comments
 (0)