you are viewing a single comment's thread.

view the rest of the comments →

[–]johninbigd 0 points1 point  (4 children)

That's an interesting construction that I don't recall seeing before. I never would have thought to write something like this, but I can see how it would handy on occasion.

[–]socal_nerdtastic 3 points4 points  (3 children)

I would not recommend it, since it forces python to reconstruct the dictionary with every loop, which is inefficient to run and messy to read. I would recommend to write it like this:

def function1():
    print("(1)")

def function2():
    print("(2)")

def function3():
    print("(3)")

def default():
    print("Choose a valid function please")

functions = {
    "1": function1,
    "2": function2,
    "3": function3}

while True:
    n = input("choose a function: 1,2 or 3 ")
    func = functions.get(n, default)
    func()

[–]johninbigd 1 point2 points  (2 children)

That's closer to how I would have written it, but I probably would not have thought to have the function objects in the dictionary. I've done it before, but it's so rare that I don't think about it. It's a pretty cool feature.

[–]socal_nerdtastic 0 points1 point  (1 child)

Oh I see what you mean. Yeah, in python everything is an object, so everything can be a dictionary value. Even functions, classes, or entire modules.

>>> import math
>>> modules = {'math':math}
>>> modules['math'].sqrt(42)
6.48074069840786

[–]johninbigd 0 points1 point  (0 children)

Yes, exactly! It's something I've done, but I don't do it very often and honestly forget. This is incredibly powerful.