Skip to content

Instantly share code, notes, and snippets.

@wonderbeyond
Created April 13, 2018 08:07
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wonderbeyond/d293e7a2af1de4873f2d757edd580288 to your computer and use it in GitHub Desktop.
Save wonderbeyond/d293e7a2af1de4873f2d757edd580288 to your computer and use it in GitHub Desktop.
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