Skip to content

Instantly share code, notes, and snippets.

@j08lue
Last active July 2, 2023 04:10
Show Gist options
  • Save j08lue/a463bab2342273ccaea6 to your computer and use it in GitHub Desktop.
Save j08lue/a463bab2342273ccaea6 to your computer and use it in GitHub Desktop.
Struct class
class Struct():
"""Create a custom class from a dictionary
Usage
-----
Initialize empty, with a dictionary, and/or
with any number of key=value pairs
Note
----
Only converts top level of nested dicts
"""
def __init__(self, entries={}, **kwargs):
self.__dict__.update(entries)
self.__dict__.update(kwargs)
def __setitem__(self, k, v):
self.__dict__[k] = v
def __getitem__(self, k):
return self.__dict__[k]
def __repr__(self):
return self.__dict__.__repr__()
def keys(self):
return self.__dict__.keys()
def iteritems(self):
return self.__dict__.iteritems()
import collections
class Struct(collections.MutableMapping):
"""Create a custom class from a dictionary
Usage
-----
Initialize empty, with a dictionary, and/or
with any number of key=value pairs
Note
----
Only converts top level of nested dicts
"""
def __init__(self, entries={}, **kwargs):
self.__dict__.update(entries)
self.__dict__.update(kwargs)
def __setitem__(self, k, v):
self.__dict__[k] = v
def __getitem__(self, k):
return self.__dict__[k]
def __delitem__(self, k):
return self.__dict__.__delitem__(k)
def __iter__(self):
return self.__dict__.__iter__()
def __len__(self):
return self.__dict__.__len__()
def __repr__(self):
return self.__dict__.__repr__()
def keys(self):
return self.__dict__.keys()
def iteritems(self):
return self.__dict__.iteritems()
@j08lue
Copy link
Author

j08lue commented Nov 17, 2014

This class is basically a dictionary but with the added feature that you can access keys as attributes, like foo.bar. The dictionary-style foo['bar'] works, too.

@j08lue
Copy link
Author

j08lue commented Nov 17, 2014

Replace iteritems with items if you use it with Python 3.

@j08lue
Copy link
Author

j08lue commented Nov 17, 2014

The second implementation uses Abstract Base Classes to make sure that the Struct actually has the same interface as a dictionary (includes delitem, iter, and len methods).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment