Search code examples
pythondynamiceval

passing in variables to eval


I am trying to dynamic run ta-lib indicators using eval, I build the below code:

sy=eval("talib."+str(i)+"("+str(df['DFF'].values)+","+str(X)+")")

where i is the ta-lib indicator, df['dff'] is a data frame holding prices and X is 5

I get the below error:

talib.MAMA([1.42 1.42 1.42 1.42 1.42 1.42 1.42 1.42 1.42 1.42 1.42 1.42 1.42 1.42
                        ^
SyntaxError: invalid syntax

Not exactly sure what I am doing wrong here, can anyone help?


Solution

  • Absolutely listen to @chris. Using eval should be an absolute last resort. You are creating a massive security hole in your program.

    If you have an object talib, and you want to call some method whose name is stored in a variable method_name, use something like:

    getattr(talib, method_name)(...arguments...)
    

    Can you explain a little bit better what it is you're trying to do?