__Missing__ Answers Missing Dict Keys
Subclass dict and implement __missing__ to give subscript lookups a custom fallback or a clearer KeyError; .get and membership checks bypass the hook.
Code
class Env(dict):
# __missing__ fires only for d[key] subscript misses; .get() and `in` never call it
def __missing__(self, key):
fallback = self.get(f"{key}_default")
if fallback is not None:
return fallback
raise KeyError(f"no setting for {key!r} and no default")
settings = Env({"log_level_default": "INFO", "region": "eu-west-1"})
print(settings["log_level"]) # miss -> falls back to log_level_default
print(settings["region"]) # direct hit, __missing__ not involved
print("api_key in settings:", "api_key" in settings) # membership never triggers the fallback
try:
settings["api_key"]
except KeyError as error:
print("missing:", error)Output
Captured from a sandboxed run of this snippet in the build pipeline.
INFO
eu-west-1
api_key in settings: False
missing: "no setting for 'api_key' and no default"What the demo falls back to
Env subclasses dict and implements missing, which fires only for d[key] subscript misses. settings[“log_level”] misses, the hook finds log_level_default holding INFO, and that fallback prints.
settings[“region”] hits directly, so the hook never runs. Membership goes the other way: “api_key” in settings never triggers missing and prints False honestly, and the later subscript raises the contextual KeyError no setting for api_key.
Practical notes
- .get() and in bypass the hook entirely.
- Raising KeyError inside missing keeps the protocol intact.
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- When does __missing__ run?
- Only when subscript access d[key] misses; the demo shows the fallback path for log_level, a direct hit for region, and a KeyError for api_key with no default.
Report a problem with this exampleOpens a pre-filled issue on GitHub.