>>> class Foo: pass >>> f = Foo() >>> f.bar = Foo() >>> f.bar.baz = Foo() >>> f.bar.baz.quux = "Found me!" >>> getattr(f, 'bar') <__main__.Foo instance at 0x01EC5918> >>> getattr(getattr(f, 'bar'), 'baz') <__main__.Foo instance at 0x01EC5A30> >>> getattr(getattr(getattr(f, 'bar'), 'baz'), 'quux') 'Found me!'
EDIT: Performed as a simple method:
>>> def dynamic_lookup(obj, dot_attrs): attr_list = dot_attrs.split(".") while attr_list: obj = getattr(obj, attr_list.pop(0)) return obj >>> f <__main__.Foo instance at 0x01EC50A8> >>> dynamic_lookup(f, 'bar.baz.quux') 'Found me!'
It adapts easily to take a list of strings (take attr_list directly instead of dot_attrs ), but I thought the notation . how the string will look cooler ...
source share