Last active
January 29, 2023 16:42
-
-
Save golobor/397b5099d42da476a4e6 to your computer and use it in GitHub Desktop.
A simple wrapper to enable dot autocompletion of Python dictionaries
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
class dotdict(dict): | |
'''A dict with dot access and autocompletion. | |
The idea and most of the code was taken from | |
http://stackoverflow.com/a/23689767, | |
http://code.activestate.com/recipes/52308-the-simple-but-handy-collector-of-a-bunch-of-named/ | |
http://stackoverflow.com/questions/2390827/how-to-properly-subclass-dict-and-override-get-set | |
''' | |
def __init__(self,*a,**kw): | |
dict.__init__(self) | |
self.update(*a, **kw) | |
self.__dict__ = self | |
def __setattr__(self, key, value): | |
if key in dict.__dict__: | |
raise AttributeError('This key is reserved for the dict methods.') | |
dict.__setattr__(self, key, value) | |
def __setitem__(self, key, value): | |
if key in dict.__dict__: | |
raise AttributeError('This key is reserved for the dict methods.') | |
dict.__setitem__(self, key, value) | |
def update(self, *args, **kwargs): | |
for k, v in dict(*args, **kwargs).iteritems(): | |
self[k] = v | |
def __getstate__(self): | |
return self | |
def __setstate__(self, state): | |
self.update(state) | |
self.__dict__ = self | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you please share an example of auto completion.