2

I have two files

test_def.py
def hi_test(a):
    return a

test_run.py

from test_def import hi_test
a = 'hi'
b = 'test'
c = 'lion'

run = "{0}_{1}".format(a, b)
run1 = run(c)
print run1

it is printing hi_test(lion) instead of executing / calling def function. can anyone help on this to execute the def function ?

Sasi
  • 31
  • 2
  • I think this is a duplicate http://stackoverflow.com/questions/4246000/python-calling-functions-dynamically – Leon Apr 21 '15 at 05:50

3 Answers3

3
import test_def
a = 'hi'
b = 'test'
c = 'lion'

run = "{0}_{1}".format(a, b)
run1 = getattr(test_def, run)(c)
print run1
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
1

it can be archive by the following method.

import test_def
a = 'hi'
b = 'test'
c = 'lion'

run = "{0}_{1}".format(a, b)
run1 = getattr(test_def,run)
run2 = run1(c)
print run2
Sasi
  • 31
  • 2
0

test_def.py

def hi_test(a):
    print a

test_run.py

from test_def import hi_test

a = 'hi'
b = 'test'
c = 'lion'

run = "{0}_{1}".format(a, b)
exec("%s('%s')"%(run, c))

Although, the first answer is better

Julia
  • 397
  • 3
  • 14