Skip to content

Instantly share code, notes, and snippets.

@digitalconceptvisuals
Created July 30, 2020 20:50
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 digitalconceptvisuals/47003d2c9d8ddc283fa6728e599e2906 to your computer and use it in GitHub Desktop.
Save digitalconceptvisuals/47003d2c9d8ddc283fa6728e599e2906 to your computer and use it in GitHub Desktop.
# 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