Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get attributes from nested objects
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