Skip to content

Instantly share code, notes, and snippets.

@bshillingford
Created August 21, 2013 22:53
Show Gist options
  • Save bshillingford/6301254 to your computer and use it in GitHub Desktop.
Save bshillingford/6301254 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
__author__ = 'brendan'
import collections
class property_dict(collections.Mapping):
"""
Dictionary wrapper that adapts a dict with a wrapper allowing property-style reads. Intended
for ease of JSON accessing.
"""
def __init__(self, d):
self._d = d
def __getitem__(self, key):
return self._d[key]
def __iter__(self):
return iter(self._d)
def __len__(self):
return len(self._d)
def __getattr__(self, attr):
if attr in self._d:
obj = self._d[attr]
if isinstance(obj, dict): # if it is a dict, apply recursively
return property_dict(self._d[attr])
return self._d[attr]
else:
raise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment