Skip to content

Instantly share code, notes, and snippets.

@foxx
Last active December 19, 2015 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foxx/5892222 to your computer and use it in GitHub Desktop.
Save foxx/5892222 to your computer and use it in GitHub Desktop.
class dict_as_class(dict):
"""Proper replacement for UserDict
Allows a dictionary to be used like a class. Really messy, thrown
together in a few minutes as a quick replacement, will probably
tidy this up later"""
def __setattr__(self, k, v):
if k in self.keys():
self[k] = v
elif not hasattr(self, k):
self[k] = v
else:
raise AttributeError, "Cannot set '%s', cls attribute already exists" % ( k, )
print k, v
def __getattr__(self, k):
if k in self.keys():
return self[k]
raise AttributeError
c = dict_as_class()
c['lol'] = 'hello'
c.lol2 = 'hello2'
c.lol2 = 'hello3'
print c
print c.lol2
c2 = dict_as_class(hello='world')
c2.wtf = 'yeah'
c.sub = c2
from pprint import pprint as p
p(c, width=5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment