Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python getattr multiple levels with values being passed as well

Tags:

python

so I've been reading up on getattr, and was wondering what the equivalent of

example = val1.val2.val3(item)

would be. So I get that you have to use nested getattr to implement multiple levels attributes

example = getattr(getattr(val1, "val2"), "val3")

but how do I represent the object being passed in?

like image 776
Krin123 Avatar asked Sep 28 '26 13:09

Krin123


2 Answers

Or you can use a neat function from the standard library operator.attrgetter. Here a little example on how to use it.

from operator import attrgetter

from collections import namedtuple

# Define some objects
Foo = namedtuple('Foo', 'attr')
Bar = namedtuple('Bar', 'subattr1')

instance = Foo(attr=Bar('this_is_my_value'))

retriever = attrgetter('attr.subattr1')
result = retriever(instance)
print(result)

This executed will give you

this_is_my_value
like image 120
flazzarini Avatar answered Oct 01 '26 04:10

flazzarini


You're almost there:

val3 = getattr(getattr(val1, "val2"), "val3")
example = val3(item)

# Or simply:
example = getattr(getattr(val1, "val2"), "val3")(item)
like image 43
ThinkChaos Avatar answered Oct 01 '26 02:10

ThinkChaos