Skip to content

Instantly share code, notes, and snippets.

@MarkRoddy
Last active September 11, 2015 18:50
Show Gist options
  • Save MarkRoddy/06e695008f496c338d77 to your computer and use it in GitHub Desktop.
Save MarkRoddy/06e695008f496c338d77 to your computer and use it in GitHub Desktop.
tamar:~ mark$ python
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(object):
... class Bar(object):
... baz = 2
...
>>> Foo.Bar.baz
2
>>> reduce(lambda x,y : getattr(x, y, "Default"), "Bar.baz".split("."), Foo)
2
>>> def getattr_chained(obj, attrs, default):
... return reduce(lambda x,y : getattr(x, y, default), attrs.split("."), obj)
...
>>> getattr_chained(Foo, "Bar.baz", "Default")
2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment