1

I am trying to run 3 different functions that has the form {}.result(). How can I use the getarr or another function so that the all 3 functions are ran within the for loop.

values = ["RSI", "MACD","ROCR"]
for k in values: 
   result= getattr(k).result()

Runs:

RSI.result()
MACD.result()
ROCR.result()
kaya3
  • 47,440
  • 4
  • 68
  • 97
ChristopherOjo
  • 237
  • 1
  • 12
  • My gut tells me that this is a scope issue, but it's hard to tell without more reference to what this line is doing: result= getattr(client, k).result() – Susan Jun 06 '21 at 07:43
  • 1
    Sorry the client part was an error. Hopefully this clears some of confusion. – ChristopherOjo Jun 06 '21 at 20:06
  • Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – kaya3 Jun 06 '21 at 22:22

2 Answers2

2

Rather than putting the names of the objects in a list, why don't you put the actual object in a list (actually a tuple here)?

for i in (RSI, MACD, ROCR):
    print(i.result())
blueteeth
  • 3,330
  • 1
  • 13
  • 23
0
class Values:
    RSI = 1
    MACD = 2
    ROCR = 3

values = Values()
names = ["RSI","MACD","ROCR"]

for i in names:
    print(getattr(values, i))

OUTPUT: 1 2 3

You will not be able to call getattr on your list as getattr gets a named attribute from your object which is equivalentof values.RSI of the code definition above. Otherwise you will get TypeError: getattr(): attribute name must be string

DaviDos
  • 1
  • 3
  • Hi I got a question related to the `getarr` function here: https://stackoverflow.com/questions/67897538/using-getarr-to-run-functions-in-python if you could take a look at it I would appreciate it. – tony selcuk Jun 09 '21 at 04:21