Skip to content

Instantly share code, notes, and snippets.

@dreispt
Last active December 29, 2015 10:29
Show Gist options
  • Save dreispt/7657154 to your computer and use it in GitHub Desktop.
Save dreispt/7657154 to your computer and use it in GitHub Desktop.
safe_getattr(): Follow an object attribute dot-notation chain to find the leaf value. If any attribute doesn't exist or has no value, just return False.
def safe_getattr(obj, attr_dot_chain, default=False):
"""
Follow an object attribute dot-notation chain to find the leaf value.
If any attribute doesn't exist or has no value, just return False.
"""
attrs = attr_dot_chain.split('.')
while attrs:
try:
obj = getattr(obj, attrs.pop(0))
except AttributeError:
return default
return obj
if __name__ == "__main__":
from datetime import datetime
x = datetime.now()
print safe_getattr(x, 'min')
print safe_getattr(x, 'min.year')
print safe_getattr(x, 'foo')
print safe_getattr(x, 'min.bar')
@dreispt
Copy link
Author

dreispt commented Nov 26, 2013

Added support for default values.

@andreparames
Copy link

Proposal, using functional methods:

def safe_getattr(obj, attr_dot_chain, default=False):
    try:
        return reduce(getattr, attr_dot_chain.split("."), obj)
    except AttributeError:
        return default

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment