API Reference#
Core Classes#
ConfigBase#
The main configuration class that provides inheritance, type validation, serialization, and instantiation capabilities.
- class zencfg.ConfigBase[source]#
Bases:
BaseModelBase class for all config objects.
Defining configs: subclass ConfigBase for each configuration category (e.g. ModelConfig), then subclass the category for each concrete choice (e.g. CNNConfig, TransformerConfig). Fields are plain annotated class attributes with optional defaults.
Selecting a subclass by name: every subclass is registered under its lowercase class name. Passing
_config_nameselects the subclass:opt: OptimizerConfig = OptimizerConfig(_config_name="adamw")
The same works from dicts and the command line (
--opt adamw).Validation: values are validated (and coerced when unambiguous) against the field’s type hint, at construction and on attribute assignment. Unknown field names raise a ValueError, invalid values a TypeError.
- instantiate(*args, recursive: bool = True, **kwargs) Any[source]#
Instantiate the target class with the config’s fields as arguments.
Creates an instance of
_target_class(a class/callable, or its fully qualified name as a string), passing every config field as a keyword argument. Nested configs that define their own_target_classare instantiated too (including inside lists, tuples and dicts), unlessrecursive=False.- Parameters:
*args (tuple) – Additional positional arguments, passed before the config fields (e.g.
optimizer_config.instantiate(model.parameters())).recursive (bool, default=True) – Recursively instantiate nested configs that define _target_class.
**kwargs (dict) – Additional keyword arguments; they override config fields with the same name.
- Returns:
An instance of the target class.
- Return type:
Any
Examples
>>> class LinearConfig(ConfigBase): ... _target_class = "torch.nn.Linear" ... in_features: int = 784 ... out_features: int = 10 >>> model = LinearConfig().instantiate() # torch.nn.Linear(in_features=784, out_features=10)
Or override the method entirely for full control:
>>> class CustomConfig(ConfigBase): ... param1: int = 42 ... def instantiate(self, *args, **kwargs): ... return MyCustomClass(self.param1, *args, **kwargs)
- model_config = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'validate_assignment': True, 'validate_default': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- to_dict(flatten: bool = False, parent_key: str = '') Dict[str, Any][source]#
Dictionary representation of this config (nested, or flattened with dotted keys).
The result always includes ‘_config_name’ entries, so it can be fed back to make_config / make_config_from_flat_dict and rebuild the exact same config, subclass choices included.
Bunch#
A dictionary-like object that exposes its keys as attributes, with special handling for nested updates.
This is what we return when we use the config.to_dict() method.
- class zencfg.bunch.Bunch(init=None)[source]#
Bases:
dictA dict exposing its keys as attributes.
Nested dicts are converted to Bunches, both at creation and on assignment, so attribute access works at any depth.
Warning
Unlike
dict.update,update()merges nested dicts recursively instead of replacing them.Examples
>>> bunch = Bunch({'a': {'b': 3, 'c': 4}, 'd': 5}) >>> bunch.a.b 3
# update merges nested dicts instead of replacing them: >>> bunch.update({‘a’: {‘b’: 5}}) {‘a’: {‘b’: 5, ‘c’: 4}, ‘d’: 5}
Loading and Instantiating Configurations#
make_config#
Create a config instance from any source: - ConfigBase class: instantiate with optional overrides - ConfigBase instance: apply overrides to a copy of instance - File path (str or Path): load a configuration class or instance from a file
- zencfg.make_config(source: Type[ConfigBase] | ConfigBase | str | Path, name: str | None = None, /, **overrides) ConfigBase[source]#
Create a config instance from any source, with overrides.
- Parameters:
source (Union[Type[ConfigBase], ConfigBase, str, Path]) – Source to create the config from: - ConfigBase class: instantiate it with the overrides - ConfigBase instance: apply the overrides to a copy - str/Path: path of a Python file to load the config from (requires name)
name (str, optional) – Name of the class or instance to load, when source is a file path.
**overrides – Values to override in the config. Nested fields use dotted keys, passed via unpacking:
make_config(cfg, **{"model.layers": 24}).
- Returns:
Config instance with overrides applied.
- Return type:
Examples
>>> # From a class >>> config = make_config(TrainingConfig, batch_size=32) >>> >>> # From a file (name of the class or instance to load is required) >>> config = make_config("configs/experiment.py", "TrainingConfig", epochs=100) >>> >>> # From an instance >>> config = make_config(TrainingConfig(), learning_rate=0.001)
make_config_from_cli#
Override any parameters of a configuration via the command-line argument. The configuration to load can be given as class, instance, or file.
- zencfg.make_config_from_cli(config_or_path: Type[ConfigBase] | ConfigBase | str | Path, config_file: str | Path | None = None, config_name: str | None = None, *, strict: bool = False) ConfigBase[source]#
Create a config instance with command-line argument overrides.
Arguments are read from sys.argv as
--key valueor--key=valuepairs, where nested fields use dots (--model.layers 24) and subclasses are selected by name (--model cnnconfig). Passing--helpprints the available fields and exits.This function supports two usage patterns:
Pass a ConfigBase class or instance directly
Load from a file, using the same API as load_config_from_file
- Parameters:
config_or_path (Union[Type[ConfigBase], ConfigBase, str, Path]) – Either: - A ConfigBase class or instance to apply CLI overrides to - A config_path root directory (when config_file is also provided) - A single file path (when config_file is None)
config_file (Union[str, Path], optional) – If provided, config_or_path is treated as the root directory and this is the file’s path relative to it (matching load_config_from_file).
config_name (str, optional) – Name of the class or instance to load. Required when loading from file.
strict (bool, default=False) – Kept for backward compatibility; validation is always on.
- Returns:
Config instance with command-line overrides applied.
- Return type:
Examples
>>> # From a class >>> config = make_config_from_cli(TrainingConfig) >>> >>> # From a file, relative to a config root directory >>> config = make_config_from_cli( ... "configs/", ... config_file="experiments/main.py", ... config_name="MainConfig", ... ) >>> >>> # From a single file path >>> config = make_config_from_cli("configs/experiment.py", config_name="TrainingConfig")
make_config_from_flat_dict#
Create a configuration instance from a flat dictionary (with dot notation to signify nested keys).
- zencfg.make_config_from_flat_dict(config_cls: Any, flat_dict: Dict[str, Any], strict: bool = False) Any[source]#
Instantiates a config class from a flat dictionary.
- Parameters:
config_cls (ConfigBase) – The config class to instantiate.
flat_dict (Dict[str, Any]) – “Flat” dict of the form {“key1”: value1, “key1.subkey”: value2, …}: a single-level dict whose keys encode nesting with dots.
strict (bool, default=False) – If True, missing required ConfigBase fields raise a ValueError. If False (default), they are filled with the category’s defaults. Value validation is always on in both modes.
- Returns:
An instance of ‘config_cls’ with the loaded values.
- Return type:
make_config_from_nested_dict#
Create a configuration instance from a nested dictionary structure.
- zencfg.make_config_from_nested_dict(config_cls: Any, nested_dict: Dict[str, Any], strict: bool = False, path: str = '') Any[source]#
Build a config instance from a nested dictionary.
Creates an instance of config_cls (or the subclass selected by a “_config_name” entry) using values from nested_dict, recursively for nested ConfigBase fields.
For ConfigBase fields with an instance default, user values are merged into that default: overriding a parameter keeps the default subclass and its other values, while passing a new “_config_name” starts fresh from the selected subclass’s own defaults.
- Parameters:
config_cls (type) – The ConfigBase subclass to instantiate.
nested_dict (dict) – Nested dictionary of values. ConfigBase fields accept either a dict of values or a bare string (treated as the “_config_name”).
strict (bool, default=False) – If True, missing required ConfigBase fields raise a ValueError. If False (default), they are filled with the category’s defaults. Value validation is always on in both modes.
path (str, optional) – Kept for backward compatibility; error messages carry full paths.
- Return type:
Instance of config_cls (or selected subclass) with the given values.
- Raises:
ValueError – On unknown keys, unknown “_config_name” values, or missing required fields.
TypeError – On values that cannot be validated against the field’s type.
load_config_from_file#
Load a configuration class or instance from a Python file.
- zencfg.load_config_from_file(config_path: str | Path, config_file: str | Path, config_name: str) Type[ConfigBase] | ConfigBase[source]#
Load a configuration from a Python file, with relative import support.
The file is imported as a regular module under a stable, path-derived name, so that:
relative imports inside the config package work,
loading the same file twice returns the same classes (isinstance and the subclass registry stay consistent),
loaded configs can be pickled within the process (e.g. inside a torch.save checkpoint). Unpickling in a different process requires the config classes to be importable there; for that, keep configs in an importable module of your project instead of loading from file.
If the file changed on disk since it was loaded, it is reloaded.
- Parameters:
config_path (Union[str, Path]) – Root directory of your config package. This is where relative imports are resolved from. Use “.” for configs in the current directory.
config_file (Union[str, Path]) – Path to the config file relative to config_path. Can be a simple name (“config.py”) or nested path (“models/bert.py”).
config_name (str) – Name of the ConfigBase class or instance to load from the file.
- Returns:
The loaded configuration class or instance.
- Return type:
Union[Type[ConfigBase], ConfigBase]
- Raises:
FileNotFoundError – If config_path/config_file doesn’t exist
ImportError – If the file cannot be imported (e.g. syntax error, import error)
AttributeError – If config_name is not found in the file
TypeError – If config_name is not a ConfigBase class or instance
ValueError – If config_file is an absolute path
Examples
>>> # Simple config in the current directory >>> config = load_config_from_file(".", "config.py", "MyConfig") >>> >>> # Nested config with relative imports >>> config = load_config_from_file( ... config_path="configs/", ... config_file="experiments/nlp/transformer.py", ... config_name="TransformerConfig" ... ) >>> # That file can use: from ...base import BaseConfig
Notes
The config file is executed as Python code. Only load configs from trusted sources: module-level code in the config will execute with full permissions.
Deprecated Functions#
Warning
The following functions are deprecated and will be removed in a future version.
cfg_from_commandline#
Deprecated since version 0.7.0: Use make_config_from_cli() instead.
Parse command-line arguments and create a configuration instance.
- zencfg.cfg_from_commandline(config_class: Type[ConfigBase], strict: bool = False) ConfigBase[source]#
Takes a Config class and returns an instance of it, with values updated from command line.
Deprecated since version 0.7.0: Use
make_config_from_cli()instead.