MANA624 MANA624 - 3 months ago 7
Python Question

Trigger Break Keyword Using Dictionary Python

I'm trying to make do with Python's lack of a switch statement and make code more efficient by using a dictionary, but I can't quite get what I'm looking for. Here's a simplified version of the code I'm working with

def zero():
print("Yo")


def one():
print("Hey")

options = {
0: zero,
1: one,
}
while True:
response = int(input("Number: "))
try:
options.get(response)()
except TypeError:
print("Not a valid response")


and what I would like to see is some way to break the loop such as
2: break
that exits the loop. Currently I'm using sys.exit(0), but was wondering if it was possible to use the break keyword

Answer

You could define a LoopBreak exception, raise that in a two function, and catch it in the loop to break:

class LoopBreak(Exception):
    pass    

def zero():
    print("Yo")

def one():
    print("Hey")

def two():
    raise LoopBreak

options = {
    0: zero,
    1: one,
    2: two
}

while True:
    response = int(input("Number: "))
    try:
        options.get(response)()
    except TypeError:
        print("Not a valid response")
    except LoopBreak:
        break

As a point of interest, this is similar to the pattern used natively by Python to stop generators; they raise a StopIteration exception when they run out of values to yield.

EDIT: As @mfripp correctly notes below, this will mask any TypeErrors that are raised during execution of zero or one. I would change the main loop to this instead (so you don't have to rely on TypeError):

while True:
    response = int(input("Number: "))
    action = options.get(response)
    if action is None:
        print("Not a valid response")
        continue
    try:
        action()
    except LoopBreak:
        break
Comments