Skip to content

Instantly share code, notes, and snippets.

@mbarkhau
Created April 13, 2011 13:20
Show Gist options
  • Save mbarkhau/917526 to your computer and use it in GitHub Desktop.
Save mbarkhau/917526 to your computer and use it in GitHub Desktop.
def getattr_sub(obj, attrs, default='__default__'):
"""
>>> getattr_sub(int, '__class__.__name__', None)
'type'
>>> getattr_sub(int, '__cleese__.__name__', 'missing')
'missing'
"""
if type(attrs) == str:
attrs = attrs.split('.')
cur = obj
for a in attrs:
cur = getattr(cur, a, '__attr_error__')
if cur == '__attr_error__':
break
if cur != '__attr_error__':
return cur
if default != '__default__':
return default
msg = "object does not have the subattattribute %s"
raise AttributeError(msg % attrs.join('.'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment