Skip to content

Instantly share code, notes, and snippets.

Created Feb 12, 2015
What would you like to do?
Easy dot notation with a dictionary using a context manager
# -*- coding: utf-8 -*-
Uses a context manager to provide a dictionary as a 'namespace' of sorts,
allowing you to use dot notation to work with the dictionary. Example:
d = {'a': 5, 'b': 10}
with named(d) as n:
# prints 5
print n.a
# reassignment changes both n and d
n.a = 'hello'
# n still has all the nice dict features:
for k, v in n.iteritems():
print k, v
# prints {'a': 'hello', 'b': 10}
print d
from contextlib import contextmanager
def named(_dict):
class named_dict(dict):
def __init__(self, d):
[setattr(self, k, v) for k, v in d.items()]
super(named_dict, self).__init__(_dict)
def __setattr__(self, name, value):
_dict[name] = value
super(named_dict, self).__setattr__(name, value)
yield named_dict(_dict)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment