Re:Lesser known parts of Python standard library – Trickster...
by BerislavLopac on Thursday September 05, 2024 @02:56AM
(#41454241)
ChainMap might be the most underrated bit in the standard library.
[ Parent
| on HN ]
Re:Lesser known parts of Python standard library – Trickster...
by stevesimmons on Thursday September 05, 2024 @09:41AM
(#41456544)
For anyone wanting some more explanation, ChainMap can be used to build nested namespaces from a series of dicts without having to explicitly merge the names in each level. Updates to the whole ChainMap go into the top-level dict.
The docs are here [0].
Some simple motivating applications:
- Look up names in Python locals before globals before built-in functions: `pylookup = ChainMap(locals(), globals(), vars(builtins))`
- Get config variables from various sources in priority order: `var_map = ChainMap(command_line_args, os.environ, defaults)`
- Simulate layered filesystems
- etc
[0] https://docs.python.org/3/library/collections.html#collectio...
Re:Lesser known parts of Python standard library – Trickster...
by BerislavLopac on Friday September 06, 2024 @06:54AM
(#41464917)
I found it perfect for structured logging, where you might want to modify some details of the logged structures (e.g. a password) without changing the underlying data.