Skip to content
Python: Keep mapping defaults with str.format_map

Python: Keep mapping defaults with str.format_map

November 26, 2026

str.format_map() uses the supplied mapping directly. That lets a dictionary subclass provide display defaults through __missing__. Expanding the same mapping into keyword arguments for str.format() does not retain that lookup behavior.

Tested on Linux with Python 3.12.14. Use Python 3.12 or newer. The example uses only the standard library and requires no network access.

Run the example

Save this as mapping_defaults.py in an empty working directory:

class DisplayFields(dict):
    def __missing__(self, key):
        return "[unset]"

fields = DisplayFields(job="nightly")
template = "{job}: owner={owner}"
print("Direct mapping:", template.format_map(fields))
print("Stored keys:", sorted(fields))
try:
    template.format(**fields)
except KeyError as error:
    print("Copied keywords missing:", error.args[0])

Run it without -O so any assertions remain enabled:

python3 mapping_defaults.py

Captured output:

Direct mapping: nightly: owner=[unset]
Stored keys: ['job']
Copied keywords missing: owner

The direct lookup produces [unset] for owner. The handler returns a value without inserting the missing key, so only job remains stored. Keyword expansion copies the present entries and the later formatting lookup raises KeyError.

Limits and cleanup

Use defaults for optional display fields. Required configuration should still fail validation when absent. This example uses a fixed, trusted template with simple field names; it does not validate arbitrary templates or nested field expressions.

After testing, remove the example script from its working directory:

rm -- mapping_defaults.py

Reference

Python 3.12 documentation

Acknowledgements

This post was created with assistance from AI.

Last updated on