Skip to content Skip to sidebar Skip to footer

Computing A Function Name From Another Function Name

In python 3.4, I want to be able to do a very simple dispatch table for testing purposes. The idea is to have a dictionary with the key being a string of the name of the function

Solution 1:

There are two parts to the problem.

The easy part is just prefixing 'text_' onto each string:

tests = {test: 'test_'+testfortestin myTestDict}

The harder part is actually looking up the functions by name. That kind of thing is usually a bad idea, but you've hit on one of the cases (generating tests) where it often makes sense. You can do this by looking them up in your module's global dictionary, like this:

tests = {test: globals()['test_'+test] fortestin myTestList}

There are variations on the same idea if the tests live somewhere other than the module's global scope. For example, it might be a good idea to make them all methods of a class, in which case you'd do:

tester = TestClass()
tests = {test: getattr(tester, 'test_'+test) for test in myTestList}

(Although more likely that code would be inside TestClass, so it would be using self rather than tester.)


If you don't actually need the dict, of course, you can change the comprehension to an explicit for statement:

fortestin myTestList:
    globals()['test_'+test]()

One more thing: Before reinventing the wheel, have you looked at the testing frameworks built into the stdlib, or available on PyPI?

Solution 2:

Abarnert's answer seems to be useful but to answer your original question of how to call all test functions for a list of function names:

deftest_f():
    print("testing f...")

deftest_g():
    print("testing g...")

myTestList = ['f', 'g']

for funcname in myTestList:
    eval('test_' + funcname + '()')

Post a Comment for "Computing A Function Name From Another Function Name"