Last active
December 29, 2015 10:29
-
-
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.
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 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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Proposal, using functional methods: