0

Is it possible to call functions in python based on string?

Lets say I have a string x="test_A;test_B;test_C"

I have a list sequence that I created based on the delimiter ";".

sequence = x.split(';')
print(sequence)

I get the following results

['test_A', test_B', 'test_C', '']

Now, I want to run the following functions in the order

  1. Test_A()
  2. Test_B()
  3. Test_C()

Is there any way in python to do that?

Try running this:

# Functions defined

def test_A(param):
    print(param)

def test_B(param):
    print(param + ' again')

def test_C(param):
    print('and ' + param + ' again')


# Dictionary defined

d = dict({
    'test_A': test_A,
    'test_B': test_B,
    'test_C': test_C
    })


# Your code

x = "test_A;test_B;test_C"

sequence = x.split(';')

print(sequence)

for func_name in sequence:
    d[func_name]('hi')

# Prints this
# hi
# hi again
# and hi again
Jun Park
  • 508
  • 1
  • 6
  • 20
deepak
  • 7
  • 5
  • I am assuming that you are giving these string values because you know the name of the functions. Which also leads to my understanding that those functions have been already defined. If that is the case, you can create a dictionary of which keys are the names of the functions and their values mapped to appropriate functions – Jun Park Dec 11 '17 at 09:33
  • Yes, I can do that but the issue is on my end is I am unable to call the functions – deepak Dec 11 '17 at 09:41
  • I edited your question to give you a working example, since the post has been closed. But it got rejected :P – Jun Park Dec 11 '17 at 10:00
  • # Functions defined \n \n def test_A(param):\n print(param)\n \n def test_B(param):\n print(param + ' again')\n \n def test_C(param):\n print('and ' + param + ' again')\n \n \n # Dictionary defined\n \n d = dict({\n 'test_A': test_A,\n 'test_B': test_B,\n 'test_C': test_C\n })\n \n \n # Your code\n \n x = "test_A;test_B;test_C"\n \n sequence = x.split(';')\n \n print(sequence)\n \n for func_name in sequence:\n d[func_name]('hi')\n \n # Prints this\n # hi\n # hi again\n # and hi again\n – Jun Park Dec 11 '17 at 10:02
  • @JunPark : It worked. Have updated the edit you suggested – deepak Dec 12 '17 at 10:33

0 Answers0