How to convert string to class attribute using Python

I know that I can get Class attributes with a string like this:

object.attribute = 'foo' x = 'attribute' getattr(object, x) >>> 'foo' 

Is there a way to "go deep" into the attributes of an object with a string? In other words, if my object contains another object, how can I get the attributes of a sub-object with a string? For instance:

 object.object.attribute 
+4
source share
3 answers

The operator.attrgetter function does the following:

 class Foo: pass f = Foo() f.bar = Foo() f.bar.baz = Foo() f.bar.baz.quux = "Found me!" import operator print operator.attrgetter("bar.baz.quux")(f) # prints "Found me!" 
+7
source

I like the recipe mentioned in this link (actually the comment is even better)

An example borrowed from Claudiu's answer (and this is also wonderful):

 class Foo: pass f = Foo() f.bar = Foo() f.bar.baz = Foo() f.bar.baz.quux = "Found me!" 

A recursive getattr that follows the dots:

 >>> rgetattr = lambda o,a: reduce(getattr, a.split('.'), o) >>> rgetattr(f, 'bar.baz.quux') 'Found me!' 

Non-lambda version:

 def rgetattr(obj, attr): return reduce(getattr, attr.split('.'), obj) 
+5
source
 >>> 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 ...

+4
source

All Articles