Skip to content
Advertisement

Given a string, call the method with the same name

I am testing multiple algorithms, and want to be able to add algorithms quickly. To do so I want to put algorithms in a list as a string, and then use the string to call the method. I’m also doing a simple timing of the algorithms and don’t want to duplicate the timer code between each method.

For example:

testData = (testSet1, testSet2, testSet3,...,testSetN)
methods = ("method1", "method2", "method3",...,"methodN")
for x in testData:
    for y in methods:
        startTime = time.time()
        #call y with x as parameter life
        endTime = time.time()

I can’t use getattr(y, x) because everything is written as a simple script. Is there an easy way to do this, or will I need to call each method?

Advertisement

Answer

Use a dictionary

testData = (testSet1, testSet2, testSet3,...,testSetN)`
methods = {"method1":method1, "method2":method2, "method3":method3,...,"methodN":methodN}
for x in testData:
    for y in methods.keys():
        startTime = time.time()
        methods[y](x)
        endTime = time.time()
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement