Skip to content

Instantly share code, notes, and snippets.

@mara004
Last active July 23, 2026 11:42
Show Gist options
  • Select an option

  • Save mara004/6e3a927b15aa484bf42f19f08c8bffca to your computer and use it in GitHub Desktop.

Select an option

Save mara004/6e3a927b15aa484bf42f19f08c8bffca to your computer and use it in GitHub Desktop.
Layered dictionary (__missing__ hook)
class layereddict (dict):
def __init__(self, layer, **kwargs):
super().__init__(**kwargs)
self._layer = layer
def __missing__(self, key):
return self._layer[key]
@mara004

mara004 commented Jul 23, 2026

Copy link
Copy Markdown
Author

Think of it like class and instance namespaces. The instance "inherits" the class namespace as a (read-only) background layer and can overshadow it.

@mara004

mara004 commented Jul 23, 2026

Copy link
Copy Markdown
Author

@mara004

mara004 commented Jul 23, 2026

Copy link
Copy Markdown
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