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?
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
You're almost there:
val3 = getattr(getattr(val1, "val2"), "val3")
example = val3(item)
# Or simply:
example = getattr(getattr(val1, "val2"), "val3")(item)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With