Last active
July 2, 2023 04:10
-
-
Save j08lue/a463bab2342273ccaea6 to your computer and use it in GitHub Desktop.
Struct class
This file contains hidden or 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
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() |
This file contains hidden or 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
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() |
Replace iteritems
with items
if you use it with Python 3.
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
This class is basically a dictionary but with the added feature that you can access keys as attributes, like
foo.bar
. The dictionary-stylefoo['bar']
works, too.