What is the right way to switch between many choices in Python
<p>I want to write something like a AI in Python:</p>

<ol>
<li><p>My first code is like this:</p>

<pre><code>def run()
    if choice_a_is_avilable:
        choice_a()
        return
    elif choice_b_is_avilable:
        if choice_b_1_is_avilable:
            choice_b_1()
            return
        elif choice_b_2_is_avilable:
            choice_b_1()
            return
    else:
        choice_c()

while 1:
    run()
</code></pre></li>
<li><p>But the code to decide if choice_a_is_avilable is quite long, and condition should bind to method. I change the code to make it more clear.</p>

<pre><code>def run():
    if(choice_a()):
        return
    elif(choice_b()):
        return
    else(choice_c()):
        return

def choice_b():
    if choice_b_is_avilable:
        if(choice_b_1()):
            return True
        elif(choice_b_2)
            return True

    return False
</code></pre></li>
<li><p>When more and more choice comes into my code, it become more and more confusing and ugly, I considered using <code>Exception</code>:</p>

<pre><code>class GetChoiceException(Exception):
    """docstring for GetChoiceException"""
    def __init__(self, *args):
        super(GetChoiceException, self).__init__(*args)


def run():
    try:
        choice_a()
        choice_b()
        choice_c()
    except GetChoiceException:
        pass

def choice_a():
    if choice_a_is_avilable:
        some_function()
        raise GetChoiceException()
</code></pre></li>
</ol>

<p>Is it a kind of abuse of <code>Exception</code>?</p>

<p>What is the write way to make choices in Python?</p>

<p>There is nothing "wrong" in your exception method if this is what you want to do. To me it looks a bit static, though. </p>

<p>Not exactly knowing your problem, one alternative to consider is having a list of available function calls if it helps. You can store functions, classes and pretty much anything you want in lists. You can then pick one by random or by choice and execute that. </p>

<pre><code>from random import choice

def foo():
    print "foo"

def bar():
    print "bar"

options = [foo,bar]
x = choice(options)
x()
</code></pre>

<p>would execute either foo() or bar(). You can then add or remove functions by modifying the contents of options list. If you just want to execute the first in list, you would call</p>

<pre><code>options[0]()
</code></pre>

<p>Hope this helps. </p>

<p>Hannu</p>

python