Created
February 12, 2015 19:28
-
-
Save eclarke/1180daba8489cff8a958 to your computer and use it in GitHub Desktop.
Easy dot notation with a dictionary using a context manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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 | |
@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