pythonweb2py-modules

How to randomly call any method from a list


Am still new to web2py and python, 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 e.g.

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 though 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, method4]

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.


Solution

  • If you want to call methods randomly use random.choice:

    def foo1():
        print "hello"
    
    def foo2():
         print "world"
    
    def foo3():
         print "goodbye"
    
    def foo4():
         print "world"
    GO = [foo1, foo2, foo3, foo4]
    
    import random
    
    def Foo():
        func = random.choice(GO)
        return func()
    In [30]: Foo()
    world
    
    In [31]: Foo()
    goodbye
    
    In [32]: Foo()
    hello
    
    In [33]: Foo()
    goodbye