Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Get attributes from nested objects
from functools import reduce
def rgetattr(obj, attr, *args):
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