Last active
July 23, 2026 11:42
-
-
Save mara004/6e3a927b15aa484bf42f19f08c8bffca to your computer and use it in GitHub Desktop.
Layered dictionary (__missing__ hook)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class layereddict (dict): | |
| def __init__(self, layer, **kwargs): | |
| super().__init__(**kwargs) | |
| self._layer = layer | |
| def __missing__(self, key): | |
| return self._layer[key] |
Author
Author
See also https://docs.python.org/3/reference/datamodel.html#object.__missing__ and https://docs.python.org/3/library/stdtypes.html#dict 1, and https://docs.python.org/3/library/collections.html#collections.defaultdict
Footnotes
-
non-linkable subsection
d[key]in supported operations ↩
Author
I wonder though, is a python layered dict backed by __missing__ as efficient as the instance -> class delegation, or less so? (Or is the former inefficient too?)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Think of it like class and instance namespaces. The instance "inherits" the class namespace as a (read-only) background layer and can overshadow it.