getattr nested attributes

Peter Otten __peter__ at web.de
Fri Aug 15 05:35:32 EDT 2008


Gregor Horvath wrote:

> Peter Otten schrieb:
> 
>> make your own function that loops over the attributes, or spell it
>> 
>>>>> reduce(getattr, "a.test".split("."), B)
>> 'test'
>> 
> 
> Thank's, but this does not work for this case:
> 
> class A(object):
>      test = "test"
> 
> class B(object):
>      a = [A(),]
> 
> In [70]: reduce(getattr, "a[0].test".split("."), B)
> ---------------------------------------------------------------------------
> <type 'exceptions.AttributeError'>        Traceback (most recent call
> last)
> 
> /<ipython console> in <module>()
> 
> <type 'exceptions.AttributeError'>: type object 'B' has no attribute
> 'a[0]'

Like the screwdriver doesn't work with a nail?

> Seems that I have to use eval ?
> I have a mapping text file (data) which contains such attributes strings
> and those attributes should be read.

When you pass data to eval() it becomes code. If you trust the source of
that text file that would be the easiest approach. Otherwise google
for 'safe eval'.

Peter



More information about the Python-list mailing list