public
Last active

  • Download Gist
dict_as_class.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
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)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.