Created
May 10, 2013 06:01
-
-
Save samba/5552665 to your computer and use it in GitHub Desktop.
Python class for masking dictionaries as objects
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
# Generic data structure for mapping named arguments directly to properties | |
# More readable code than using dictionaries... | |
# Usage: | |
# mystruct = Struct(value1 = "x", value2 = "y", value3 = "z") | |
# print mystruct.value1 | |
# >> x | |
class Struct(object): | |
def __init__(self, **entries): | |
Struct.update(self, entries) | |
def __repr__(self): | |
return repr(self.__dict__) | |
def __getattr__(self, name): | |
if(name == '__dict__'): | |
return self.__dict__ | |
else: | |
return self.__dict__.get(name) | |
def __setattr__(self, name, value): | |
self.__dict__[name] = value | |
def __getitem__(self, name): | |
return self.__getattr__(name) | |
def __setitem__(self, name, value): | |
return self.__setattr__(name, value) | |
# This method allows recursive mapping of Dictionaries to Structs | |
@classmethod | |
def update(cls, self, entries): | |
self.__dict__.update(entries) | |
for k in self.__dict__.keys(): | |
if isinstance(self.__dict__[k], dict): | |
self.__dict__[k] = Struct(** self.__dict__[k]) | |
return self |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment