Config-Based Instantiation

These utility functions allow you to dynamically instantiate classes from a configuration dictionary - especially useful when working with environments, plugins, or service registries.

This pattern complements ServiceLocator, enabling flexible, config-driven architecture.

It supports a variety of use cases:

  • Creating a single object from config

  • Creating multiple objects (e.g. a list of loggers)

  • Mixing instantiated objects with raw config values

  • Registering objects into the ServiceLocator automatically

Example

This example demonstrates how to define a config dictionary that describes services and loggers, then dynamically instantiate those classes using a class map. Each object is created and optionally registered into the ServiceLocator for global access.

from pattern_kit import build_from_config
# from .databases import PostgresDatabase, MongoDatabase
# from .loggers import ConsoleLogger, SlackLogger

config = {
    "Database": {"class": "PostgresDatabase", "args": {"url": "localhost"}},
    "Loggers": [
        {"class": "SlackLogger", "args": {"channel": "#general"}},
        {"class": "ConsoleLogger"}
    ]
}

class_map = {
    "PostgresDatabase": PostgresDatabase,
    "MongoDatabase": MongoDatabase,
    "SlackLogger": SlackLogger,
    "ConsoleLogger": ConsoleLogger,
}

components = build_from_config(config, class_map=class_map, register=True)

# from pattern_kit import ServiceLocator
# print(ServiceLocator)
#
# Registered services:
# Database: object of type PostgresDatabase
# Loggers:
#  - object of type SlackLogger
#  - object of type ConsoleLogger

Loading from YAML

You can load configuration files using PyYAML and pass them directly to build_from_config():

import yaml
from pattern_kit import build_from_config

with open("config.yaml", "r") as f:
    config = yaml.safe_load(f)

components = build_from_config(config, class_map=my_class_map)

Supported Config Formats

The build_from_config() function accepts any dictionary-style config.

You can load these from common file formats:

  • YAML via PyYAML (yaml.safe_load(…))

  • JSON via the standard json module

  • TOML via tomli or tomllib (Python 3.11+)

  • INI via configparser (convert to dict manually)

  • XML via xmltodict or custom parsing

After loading, simply pass the resulting dict to build_from_config().

API Reference

pattern_kit.utils.config_loader.resolve_class(class_name: str, class_map: dict[str, type] = None) type[source]

Resolve a class either from a provided class map or by importing a dotted path.

Parameters:
  • class_name (str) – The class name or full import path.

  • class_map (dict[str, type], optional) – A dictionary of available classes by name.

Returns:

The resolved class object.

Return type:

type

Raises:

ValueError – If the class cannot be resolved from the map or path.

pattern_kit.utils.config_loader.build_object(cfg: dict[str, Any], class_map: dict[str, type] = None) Any[source]

Instantiate an object from a config dict with ‘class’ and optional ‘args’.

Parameters:
  • cfg (dict) – Must contain ‘class’ and optionally ‘args’.

  • class_map (dict[str, type], optional) – Safe list of allowed classes.

Returns:

Instantiated object.

Return type:

Any

pattern_kit.utils.config_loader.build_from_config(config: dict[str, dict | list], class_map: dict[str, type] = None, register: bool = False, register_raw: bool = False) dict[str, Any][source]

Build one or more objects from a config dictionary.

Supports both object configs (with ‘class’ + optional ‘args’) and raw config entries (passed through as-is).

Parameters:
  • config (dict) – The full config mapping keys to: - object configs (dict with ‘class’) - lists of object configs - raw values (passed through)

  • class_map (dict[str, type], optional) – Optional map of allowed classes.

  • register (bool) – If True, registers each built object with ServiceLocator[key].

  • register_raw (bool) – If True, also register raw (non-built) values in the ServiceLocator.

Returns:

Dictionary of created or passed-through values by key.

Return type:

dict[str, Any]