Skip to content

Instantly share code, notes, and snippets.

@golobor
Last active January 29, 2023 16:42
Show Gist options
  • Select an option

  • Save golobor/397b5099d42da476a4e6 to your computer and use it in GitHub Desktop.

Select an option

Save golobor/397b5099d42da476a4e6 to your computer and use it in GitHub Desktop.
A simple wrapper to enable dot autocompletion of Python dictionaries
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
@sgoelman

Copy link
Copy Markdown

Can you please share an example of auto completion.

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