← Back to Python

All Topics

Advertisement

Learn/Python/Advanced Python

ChainMap in Practice

Topic: Data Structures

Advertisement

Introduction

Practical applications of ChainMap for organizing hierarchical data and configurations.

Configuration System

from collections import ChainMap

class Config:
    def __init__(self, defaults, environment, runtime):
        self.chain = ChainMap(runtime, environment, defaults)
    
    def get(self, key, default=None):
        return self.chain.get(key, default)
    
    def __getitem__(self, key):
        return self.chain[key]

defaults = {"db_host": "localhost", "db_port": 5432}
env = {"db_host": "prod.example.com"}
runtime = {"db_port": 5433}

config = Config(defaults, env, runtime)
print(config["db_host"])  # prod.example.com
print(config["db_port"]) # 5433

Namespace Stacking

from collections import ChainMap

builtin_vars = {"__name__": "__main__", "print": print}
global_vars = {"count": 0, "data": []}
local_vars = {"count": 5, "temp": "value"}

all_vars = ChainMap(local_vars, global_vars, builtin_vars)
print(all_vars["count"])  # 5 (local)

Practice Problems

  1. Build layered configuration system
  2. Implement scoped variable access
  3. Create namespace with inheritance
  4. Merge environment configs
  5. Build template context system

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →