Created
April 13, 2011 13:20
-
-
Save mbarkhau/917526 to your computer and use it in GitHub Desktop.
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
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