How do I iterate over imported methods in a list?

14 views
Skip to first unread message

Maurice Waka

unread,
Jul 10, 2014, 12:17:25 PM7/10/14
to web...@googlegroups.com
in my web2py app, i created this code that works well in python shell.

python modules:
#The methods work in such a way that a user inputs an equation query to get an answer. If it is an addition, method1 works it out, the same to other methods being invoked to performing different codes

def method1():# to do additions
    name = input('Please Enter equation here: ').lower()
    if '1 + 1':
        answer = code
        return answer

def method2():# to do subtractions
    name = input('Please Enter equation here: ').lower()
    if '1 - 1':
        answer = code
        return answer


in the controller, I imported the methods as follows. There are many more methods than these shown

from applications ...... import method1
from applications ...... import method2
from applications ...... import method3
from applications ...... import method4

method1 = method1
method1 = method2
method1 = method3
method1 = method4

G0 = [method1, method2, method3, m3thod4]

def Foo():
    code..
    for (func) in G0:
        return func()

The problem is that only method1 which is at position[0] in the list is invoked and not other methods. I want to randomly call any method when a user inputs any query.

Anthony

unread,
Jul 10, 2014, 12:38:49 PM7/10/14
to web...@googlegroups.com
method1 = method1
method1 = method2
method1 = method3
method1 = method4

Why do you make four assignments to the same variable?

G0 = [method1, method2, method3, m3thod4]

def Foo():
    code..
    for (func) in G0:
        return func()

The problem is that only method1 which is at position[0] in the list is invoked and not other methods. I want to randomly call any method when a user inputs any query.

Your function returns within the first loop iteration, so of course it only runs the first method. What are you really trying to do?

Anthony
 

Rufus

unread,
Jul 11, 2014, 12:17:13 AM7/11/14
to web...@googlegroups.com

It is very difficult to see what you are trying to accomplish in those functions.  But if your intent is to run through multiple functions, returning
results, one way is with "yield":

def runfuncs():
    for func in g0:
        yield(func())
       
for result in runfuncs():
    print "result: ",result
   

Reply all
Reply to author
Forward
0 new messages