brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's dict merge operator | layers defaults and overrides

Python
~/tips/tip-python-dict-merge-operator

settings = defaults | overrides

Combine default settings with user overrides in one readable expression.

Since Python 3.9 dicts support | and |=. I like it for the classic pattern of default settings plus whatever the user changed.

defaults = {"host": "127.0.0.1", "port": 8080, "debug": False}
overrides = {"port": 9000}

settings = defaults | overrides
print(settings)   # {'host': '127.0.0.1', 'port': 9000, 'debug': False}

settings |= {"debug": True}   # update in place

The right side wins when a key exists on both sides. a | b builds a new dict and leaves both originals alone, while a |= b changes a in place, just like a.update(b).

It reads more clearly to me than {**defaults, **overrides}, and you can chain several layers: defaults | file_config | env_config, where each later one wins.

The merge is shallow, and that’s the thing to watch with config. If defaults has a nested "db": {...} section and the override has only {"db": {"port": 5433}}, the whole db dict gets replaced and you lose the host and user that were in the default. For nested config you need a small recursive merge function, or keep the config flat.

Further reading: dict union operators, PEP 584

Going deeper: Guide: advanced tmux, a config that grows with you, formats, layouts and more

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link