Skip to content

@foxx /dict_as_class.py
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.