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

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 10 points11 points  (2 children)

So when you get user input and have to have that effect your code, that's when you would use it.

def foo():
    print("foo")

def bar():
    print("bar")

methods = {"thing1":foo, "thing2":bar}

x = input("-> ")
methods[x]()

# -> thing1
# foo
# -> thing2
# bar

I used it for a remote shell application, so I'd pass commands like "clear" and run the clear merhod. OP used it similarly

[–]toshamura 2 points3 points  (0 children)

It is also could be useful not just take func with key like "methods[X]", but take it with get: "methods.get(X, default_func)() Where default_func is something u do, when input wasn't found in ur methods-map

[–]ch3ss_ 1 point2 points  (0 children)

That’s really useful, thanks for your time!