0
list=[ 'attribute1', 'attribute2', 'attribute3']
for x in list:
  foo = bar.x ()

Error:
AttributeError: module 'bar' has no attribute 'x'

bar has all attributes but I don't know how to pass the variable as an attribute, there should be a way to do bar.attribute1 bar.attribute2 bar.attribute3 without literally specifying it

the solution:

list=[ 'attribute1', 'attribute2', 'attribute3']
for x in list:
  foo = bar
  foo = getattr(foo, x) ()
  • You cannot "pass a variable as an attribute". You can pass a *string* that can be used to dynamically access attirbutes using `getattr`. – juanpa.arrivillaga Oct 18 '22 at 20:05
  • Note, you *could* have done something like `exec(f"foo = bar.{x}()")` but this is hacky and brittle (behaves differently in local vs global namespaces..., if you want to make it more resiliant you have to take care with the arguments you pass to exec). Use `foo = getattr(bar, x)()` instead – juanpa.arrivillaga Oct 18 '22 at 20:06

0 Answers0