Claude Code for OmegaConf: Hierarchical Config in Python — Claude Skills 360 Blog
Blog / AI / Claude Code for OmegaConf: Hierarchical Config in Python
AI

Claude Code for OmegaConf: Hierarchical Config in Python

Published: March 18, 2028
Read time: 5 min read
By: Claude Skills 360

OmegaConf manages hierarchical YAML-based configuration with interpolation and merging. pip install omegaconf. Create: from omegaconf import OmegaConf; cfg = OmegaConf.create({"db": {"host": "localhost", "port": 5432}}). cfg.db.host → “localhost”. YAML: cfg = OmegaConf.load("config.yaml"). Merge: OmegaConf.merge(base_cfg, override_cfg) — deep merge, override wins. CLI: OmegaConf.from_dotlist(["db.host=prod.db", "debug=true"]). Interpolation: {"host": "db", "url": "postgres://${host}:5432/app"} → url resolves to “postgres://db:5432/app”. MISSING: from omegaconf import MISSING; class DBConfig: password: str = MISSING — raises if not supplied. Struct: @dataclass; class Config: debug: bool = False. cfg = OmegaConf.structured(Config). OmegaConf.is_missing(cfg, "password"). Readonly: OmegaConf.set_readonly(cfg, True) — raises on write. OmegaConf.is_readonly. to_yaml: OmegaConf.to_yaml(cfg) → YAML string. to_container: OmegaConf.to_container(cfg, resolve=True) → plain dict. Select: OmegaConf.select(cfg, "db.host", default="localhost"). Resolver: OmegaConf.register_new_resolver("env", lambda k: os.environ.get(k, "")). ${env:DB_HOST}. Hydra: @hydra.main(config_path="conf", config_name="config"). Claude Code generates OmegaConf config hierarchies, YAML loaders, and ML experiment configs.

CLAUDE.md for OmegaConf

## OmegaConf Stack
- Version: omegaconf >= 2.3 | pip install omegaconf
- Create: OmegaConf.create({"db": {"host": "localhost"}}) | OmegaConf.load("cfg.yaml")
- Access: cfg.db.host | cfg["db"]["host"] — dot and bracket access
- Merge: OmegaConf.merge(base, override) — deep merge, override wins
- Interpolation: "${db.host}" → value of db.host key
- Structured: @dataclass + OmegaConf.structured(Config) for typed configs
- MISSING: field has no value — accessing raises MissingMandatoryValue

OmegaConf Configuration Pipeline

# app/config.py — OmegaConf hierarchical config, merging, and structured types
from __future__ import annotations

import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

from omegaconf import MISSING, DictConfig, OmegaConf, open_dict


# ─────────────────────────────────────────────────────────────────────────────
# 1. Structured config dataclasses
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class DatabaseConfig:
    host:     str = "localhost"
    port:     int = 5432
    name:     str = "appdb"
    user:     str = "postgres"
    password: str = MISSING     # Required — must be supplied at runtime


@dataclass
class RedisConfig:
    host: str = "localhost"
    port: int = 6379
    db:   int = 0
    ttl:  int = 3600


@dataclass
class ServerConfig:
    host:    str  = "0.0.0.0"
    port:    int  = 8000
    debug:   bool = False
    workers: int  = 4


@dataclass
class AppConfig:
    app_name:    str          = "MyApp"
    environment: str          = "development"
    log_level:   str          = "INFO"
    db:          DatabaseConfig = field(default_factory=DatabaseConfig)
    redis:       RedisConfig    = field(default_factory=RedisConfig)
    server:      ServerConfig   = field(default_factory=ServerConfig)


# ─────────────────────────────────────────────────────────────────────────────
# 2. Config creation helpers
# ─────────────────────────────────────────────────────────────────────────────

def create_default_config() -> DictConfig:
    """Create a typed OmegaConf DictConfig from the AppConfig dataclass."""
    return OmegaConf.structured(AppConfig)


def load_yaml(path: str | Path) -> DictConfig:
    """Load a YAML config file into a DictConfig."""
    return OmegaConf.load(str(path))


def from_dotlist(overrides: list[str]) -> DictConfig:
    """
    Create a DictConfig from a list of "key=value" override strings.
    "db.host=prod.db", "server.debug=true", "db.port=5433"
    """
    return OmegaConf.from_dotlist(overrides)


def from_env(prefix: str = "APP__") -> DictConfig:
    """
    Build a DictConfig from environment variables with double-underscore nesting.
    APP__DB__HOST → db.host
    Strips the prefix, lowercases keys, and converts __ to dots.
    """
    items = {}
    for key, value in os.environ.items():
        if key.upper().startswith(prefix.upper()):
            stripped = key[len(prefix):]
            nested_key = stripped.replace("__", ".").lower()
            items[nested_key] = value
    return OmegaConf.from_dotlist([f"{k}={v}" for k, v in items.items()])


# ─────────────────────────────────────────────────────────────────────────────
# 3. Merging and overriding
# ─────────────────────────────────────────────────────────────────────────────

def merge(*configs: DictConfig) -> DictConfig:
    """
    Deep-merge multiple DictConfigs in order (later wins).
    OmegaConf.merge(base, dev_overrides, cli_overrides)
    """
    return OmegaConf.merge(*configs)


def load_with_overrides(
    base_path: str | Path,
    override_path: str | Path | None = None,
    cli_overrides: list[str] | None = None,
) -> DictConfig:
    """
    Load a base YAML, optionally merge an override YAML, then apply CLI overrides.
    Priority: CLI > override_path > base_path
    """
    cfg = load_yaml(base_path)

    if override_path and Path(override_path).exists():
        override = load_yaml(override_path)
        cfg = OmegaConf.merge(cfg, override)

    if cli_overrides:
        cli = from_dotlist(cli_overrides)
        cfg = OmegaConf.merge(cfg, cli)

    return cfg


def apply_env_overrides(cfg: DictConfig, prefix: str = "APP__") -> DictConfig:
    """Apply environment variable overrides on top of an existing config."""
    env_cfg = from_env(prefix=prefix)
    return OmegaConf.merge(cfg, env_cfg)


# ─────────────────────────────────────────────────────────────────────────────
# 4. Access helpers
# ─────────────────────────────────────────────────────────────────────────────

def get(cfg: DictConfig, key: str, default: Any = None) -> Any:
    """
    Safe dot-notation access with default.
    get(cfg, "db.host", "localhost")
    """
    return OmegaConf.select(cfg, key, default=default)


def is_missing(cfg: DictConfig, key: str) -> bool:
    """Return True if a key is set to MISSING."""
    try:
        return OmegaConf.is_missing(cfg, key)
    except Exception:
        return True


def check_required(cfg: DictConfig, required_keys: list[str]) -> list[str]:
    """Return a list of required keys that are MISSING or unresolved."""
    missing = []
    for key in required_keys:
        if is_missing(cfg, key):
            missing.append(key)
    return missing


# ─────────────────────────────────────────────────────────────────────────────
# 5. Serialization
# ─────────────────────────────────────────────────────────────────────────────

def to_yaml(cfg: DictConfig, resolve: bool = False) -> str:
    """Serialize config to a YAML string."""
    return OmegaConf.to_yaml(cfg, resolve=resolve)


def to_dict(cfg: DictConfig, resolve: bool = True) -> dict[str, Any]:
    """Convert DictConfig to a plain Python dict."""
    return OmegaConf.to_container(cfg, resolve=resolve, throw_on_missing=False)


def save_yaml(cfg: DictConfig, path: str | Path, resolve: bool = False) -> None:
    """Write config to a YAML file."""
    Path(path).write_text(to_yaml(cfg, resolve=resolve), encoding="utf-8")


# ─────────────────────────────────────────────────────────────────────────────
# 6. Readonly / freeze
# ─────────────────────────────────────────────────────────────────────────────

def freeze(cfg: DictConfig) -> DictConfig:
    """Return a read-only copy of the config. Raises on modification."""
    OmegaConf.set_readonly(cfg, True)
    return cfg


def unfreeze_context(cfg: DictConfig):
    """Context manager to temporarily allow writes to a readonly config."""
    return open_dict(cfg)


# ─────────────────────────────────────────────────────────────────────────────
# 7. Custom resolvers
# ─────────────────────────────────────────────────────────────────────────────

def register_env_resolver() -> None:
    """
    Register an ${env:VAR_NAME} interpolation resolver.
    In YAML: url: "postgres://${env:DB_HOST}:5432/app"
    """
    try:
        OmegaConf.register_new_resolver(
            "env",
            lambda key, default="": os.environ.get(key, default),
            replace=False,
        )
    except Exception:
        pass   # already registered


def register_path_resolver() -> None:
    """
    Register a ${path:rel/path} resolver that makes the path absolute.
    In YAML: output_dir: "${path:outputs}"
    """
    try:
        OmegaConf.register_new_resolver(
            "path",
            lambda rel: str(Path(rel).resolve()),
            replace=False,
        )
    except Exception:
        pass


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    # Register resolvers
    register_env_resolver()
    register_path_resolver()

    print("=== Structured config ===")
    cfg = create_default_config()
    print(f"  app_name:  {cfg.app_name}")
    print(f"  db.host:   {cfg.db.host}")
    print(f"  db.port:   {cfg.db.port}")
    print(f"  db.password MISSING: {is_missing(cfg, 'db.password')}")

    print("\n=== Merge (override) ===")
    base = OmegaConf.create({
        "db": {"host": "localhost", "port": 5432},
        "debug": False,
        "log_level": "INFO",
    })
    prod_override = OmegaConf.create({
        "db": {"host": "prod.db.example.com"},
        "log_level": "WARNING",
    })
    cli_override = from_dotlist(["debug=false", "db.port=5433"])

    merged = merge(base, prod_override, cli_override)
    print(f"  db.host:   {merged.db.host}")
    print(f"  db.port:   {merged.db.port}")
    print(f"  log_level: {merged.log_level}")
    print(f"  debug:     {merged.debug}")

    print("\n=== Interpolation ===")
    interp_cfg = OmegaConf.create({
        "db_host": "mydb.example.com",
        "db_port": 5432,
        "db_url":  "postgresql://${db_host}:${db_port}/app",
    })
    print(f"  db_url: {interp_cfg.db_url}")

    print("\n=== YAML output ===")
    print(to_yaml(merged))

    print("=== to_dict ===")
    d = to_dict(merged)
    for k, v in d.items():
        print(f"  {k}: {v!r}")

    print("\n=== readonly ===")
    frozen = freeze(OmegaConf.create({"x": 1}))
    try:
        frozen.x = 2
    except Exception as e:
        print(f"  Got expected error: {type(e).__name__}: {e}")

    with unfreeze_context(frozen):
        frozen.x = 99
        print(f"  After unfreeze write: x={frozen.x}")

For the configparser alternative — Python’s configparser reads INI files into flat string sections with no type coercion, no nesting, no YAML, and no merging; OmegaConf reads YAML (or dict/dataclass), coerces types, supports nested keys like cfg.db.host, and merges configs with override semantics — OmegaConf is the right tool when your config is hierarchical and type-safe. For the hydra-core relationship — Hydra is built on top of OmegaConf and adds @hydra.main(), multi-run sweeps, config groups, and command-line override parsing; if you need just the config object (not the CLI launcher), OmegaConf alone is lighter and works outside of Hydra’s opinionated app structure. The Claude Skills 360 bundle includes OmegaConf skill sets covering OmegaConf.create(), OmegaConf.load() YAML, OmegaConf.merge() deep merge, @dataclass structured configs with MISSING, OmegaConf.select() safe access, OmegaConf.to_yaml()/to_container(), register_new_resolver() for ${env:KEY}, from_dotlist() CLI overrides, from_env() double-underscore env vars, load_with_overrides() multi-source loading, freeze()/open_dict() readonly management, and check_required() MISSING validation. Start with the free tier to try hierarchical configuration code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free