Skip to content

Instantly share code, notes, and snippets.

@jdevera
Created November 15, 2012 11:08
Show Gist options
  • Save jdevera/4078046 to your computer and use it in GitHub Desktop.
Save jdevera/4078046 to your computer and use it in GitHub Desktop.
Python Data Structure Objectifier
#!/usr/bin/env python
"""
An objectifier for python data structures based on standard containers.
Based on sveral answers to this stackoverflow question:
http://stackoverflow.com/q/1305532/116957
Licensed under Creative Commons Attribution-ShareAlike
http://creativecommons.org/licenses/by-sa/3.0/
"""
class Struct(object):
def __init__(self, d):
seqs = tuple, list, set, frozenset
for k, v in d.iteritems():
if isinstance(v, dict):
setattr(self, k, self.__class__(v))
elif isinstance(v, seqs):
setattr(self, k, type(v)(self.__class__(sv) if isinstance(sv, dict) else sv for sv in v))
else:
setattr(self, k, v)
def __repr__(self):
return '{%s}' % str(', '.join('%s : %s' % (k, repr(v)) for (k, v) in self.__dict__.iteritems()))
if __name__ == '__main__':
s = Struct( {
'a1' : {
'a2' : {
'a3' : 'stuff'
},
'b2' : [ 1, 2, {
'b3' : 'otherstuff'
}]
}
})
print s
print s.a1.a2.a3
print s.a1.b2
print s.a1.b2[0]
print s.a1.b2[2]
print s.a1.b2[2].b3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment