0

I want to call a function from another script according to a string I pass in my current script. For example: I have different functions in Entry, I want to choose which one to run.

import Entry
def ma_exec(entry = 'longShort'):
    if entry == 'longShort':
        entryStrategy = Entry.longShort
    entryStrategy(PositionTable, Signal)

But in this way I will have to write so many if for each different functions in Entry. Can I do something similar as:

def ma_exec(entry = 'longShort'):
    entryStrategy = Entry.entry

So that I can run different functions according to the String value I pass to this ma_exec function? I know this line above is not right, is there a good way to solve my problem?

Dylan
  • 915
  • 3
  • 13
  • 20
  • 2
    Could you use a dictionary to relate the string passed to the function to the function pointer? I.e. One entry of the dictionary would have 'longShort' as the key and Entry.longShort as the value. Maybe for each string you would have a corresponding function pointer. – Bobby Durrett Oct 27 '17 at 23:17

1 Answers1

0

This is probably a good case for Python's eval() function. Try the code below:

eval("Entry." + entry + "(PositionTable, Signal)")

To my knowledge, you can only do this in an interpreted language like Python.

Barmar
  • 741,623
  • 53
  • 500
  • 612