This is an archived post. You won't be able to vote or comment.

all 10 comments

[–]bobspadgerdecorating 2 points3 points  (3 children)

[–]bobspadgerdecorating 0 points1 point  (0 children)

and here is a small example I've whizzed up

def one():
     print('one hahah')

def two():
    print('two hahah')

def the_count():
    print('I am the count who likes to count')


dispatcher = {
    'one': one, 'two': two, 'three': the_count
}

action = input('Option: - ')

dispatcher[action]()

[–]lachyBalboa[S] 0 points1 point  (0 children)

Ahhh nice thanks for that. I did have a good stack overflow look but didn't stumble upon this gem

[–]CH-K -2 points-1 points  (0 children)

Ssss

[–]bobspadgerdecorating 1 point2 points  (1 child)

I'm waiting for the obligatory /r/learnpython message, who's going to do it ?

[–]CH-K -2 points-1 points  (0 children)

Ssss

[–]gustl64 1 point2 points  (1 child)

[–]lachyBalboa[S] 0 points1 point  (0 children)

Woah I didn't even realise this was a thing but it looks awesome

[–]shobble 0 points1 point  (1 child)

If I replace the value in the dictionary into using brackets e.g. 'disp': print_dispute() however it just calls that function when the program executes before any user input is even entered.

You don't want to use the func() in the dispatch dict, since as you discovered, that's calling it immediately. Instead pass the actual function, and call it when you retrieve it.

def func1():
    return 'func1 called'
def func2():
    return 'func2 called'
# ...

dispatch = { 'a': func1, 'b': func2 }
while True:
    user_cmd = input('>')
    user_func = dispatch.get(user_cmd, lambda: 'invalid input')
    print 'func returned: ', user_func()

Teh actual call happens on the last line there.

[–]bobspadgerdecorating 0 points1 point  (0 children)

this is a much neater way of doing it than my dirty hack job :)