Skip to content

Instantly share code, notes, and snippets.

@dhilst
Last active May 27, 2020 06:49
Show Gist options
  • Save dhilst/bb6eeae40e38cb76b890ded77f319dc8 to your computer and use it in GitHub Desktop.
Save dhilst/bb6eeae40e38cb76b890ded77f319dc8 to your computer and use it in GitHub Desktop.
def get(obj, attr, default=None):
"""
Fetch an attribute deeply nested on an object or dict, return `default` if not found
>>> class Foo: pass
>>> f = Foo()
>>> f.a = Foo()
>>> f.a.b = Foo()
>>> f.a.b.c = True
>>> get(f, "a.b.c")
True
>>> get(f, "a.b.d") is None
True
>>> d = {'a': {'b': {'c': True}}}
>>> get(d, 'a.b.c')
True
>>> get(d, 'a.b.d') is None
True
"""
attrs = attr.split('.')
temp = obj
for attr in attrs:
try:
if isinstance(temp, dict):
temp = temp[attr]
else:
temp = getattr(temp, attr)
except (KeyError, AttributeError):
return default
return temp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment