Created
April 13, 2018 08:07
-
-
Save wonderbeyond/d293e7a2af1de4873f2d757edd580288 to your computer and use it in GitHub Desktop.
Get attributes from nested objects
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
from functools import reduce | |
def rgetattr(obj, attr, *args): | |
"""See https://stackoverflow.com/questions/31174295/getattr-and-setattr-on-nested-objects""" | |
def _getattr(obj, attr): | |
return getattr(obj, attr, *args) | |
return reduce(_getattr, [obj] + attr.split('.')) | |
import os.path | |
print(rgetattr(os, 'path.sep')) | |
print(rgetattr(os, 'path.sepx', None)) | |
print(rgetattr(os, 'path.sepx', '--')) | |
print(rgetattr(os, 'path.sepx')) # will raise AttributeError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment