Last active
May 27, 2020 06:49
-
-
Save dhilst/bb6eeae40e38cb76b890ded77f319dc8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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