7 Practical EasyDict Patterns for Everyday Projects
- Simple attribute access
Use EasyDict to access dictionary keys like attributes for cleaner code:
python
from easydict import EasyDictcfg = EasyDict({‘host’: ‘localhost’, ‘port’: 8080})print(cfg.host) # localhost
- Nested configuration objects
Represent nested configs without repeated bracket syntax:
python
cfg = EasyDict({‘db’: {‘user’: ‘app’, ‘pass’: ‘secret’, ‘host’: ‘db.local’}})print(cfg.db.user)
- Default values with get-style fallback
Combine EasyDict with dict.get or set defaults while keeping attribute access:
python
cfg = EasyDict()cfg.setdefault(‘timeout’, 30)print(cfg.timeout)
- Merging and overlaying settings
Merge multiple dicts into a single EasyDict for environment or override layers:
python
base = EasyDict({‘debug’: False, ‘timeout’: 30})env = EasyDict({‘debug’: True})config = EasyDict({base, **env})
- Passing structured settings to functions
Use EasyDict for clean function signatures and attribute-style access inside functions:
python
def start_server(opts): host, port = opts.host, opts.portstart_server(EasyDict({‘host’: ‘0.0.0.0’, ‘port’: 8000}))
- Converting to/from JSON or YAML
Serialize and deserialize configs while preserving EasyDict convenience:
python
import jsoncfg = EasyDict(json.loads(‘{“a”:1,“b”:2}’))s = json.dumps(cfg) # works because EasyDict is dict-like
- Iterating and validation helpers
Treat EasyDict like a dict for loops and add simple validators:
python
cfg = EasyDict({‘retries’: 3, ‘mode’: ‘prod’})for k, v in cfg.items(): validate(k, v)
Notes: EasyDict is a lightweight convenience wrapper—use it for readability and prototyping; for complex validation or immutability prefer dedicated config libraries.
Leave a Reply