Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# auto inherits a dictionary
class auto(dict):
# if caller did univ.college
def __getattr__(self, name):
try:
# check if its there
return dict.__setitem__(self, name)
except:
# if not, create it on the fly
dict.__setitem__(self, name, auto())
return dict.__getitem__(self, name)
# if caller did univ.college = value
def __setattr__(self, name, value):
# set it in internal dict
dict.__setitem__(self, name, value)
# if caller did univ['college]
def __getitem__(self, value):
try:
# if found return it
return dict.__getitem__(self, value)
except:
# if not, create it on the fly
dict.__setitem__(self, value, auto())
return dict.__getitem__(self, value)
univ = auto()
univ.college.stream.year = "A+"
print(univ)
univ2 = auto()
univ2['college']['stream']['year'] = "A+"
print(univ2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment