getattr nested attributes
Wojtek Walczak
gminick at bzt.bzt
Fri Aug 15 05:56:54 EDT 2008
On Fri, 15 Aug 2008 11:12:04 +0200, Gregor Horvath wrote:
> 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]'
>
> Seems that I have to use eval ?
Nope. Always ask getattr for small things and it will like you:
>>> getattr(getattr(B, 'a')[0], 'test')
'test'
>>>
it works because:
>>> getattr(B, 'a') == B.a
True
>>> getattr(B, 'a')[0] == B.a[0]
True
>>>
--
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
More information about the Python-list
mailing list