Question

I have a dict that stores two functions like this:

def quick():
    print("dex is 1")

def strong():
    print("str is 1")

def start():
    suffix = {"quick" : quick(), "strong" : strong()}
    suffix.get("quick")

start()

And then I execute this code, the output is:

dex is 1
str is 1

It seems that my dict.get() didn't work well here. Why are both of the functions executed, and not just the quick function?

Was it helpful?

Solution

You have to use functions as variables in your dict, and make a call only when needed:

def quick():
    print("dex is 1")

def strong():
    print("str is 1")

def start():
# without a `()` after a function's name, the function is just a variable, 
# waiting for a call
    suffix = {"quick" : quick, "strong" : strong}
    suffix.get("quick")() # and here is the actual call to the function

start()

OTHER TIPS

Because there are () after the function names. Return values of the function calls are used for dictionary values instead of functions.

def start():
    suffix = {"quick" : quick(), "strong" : strong()}
    #                        ^^                   ^^

Fix:

def start():
    suffix = {"quick" : quick, "strong" : strong} # Use function itself.
    func = suffix.get("quick")  # Get function object.
    func()                      # Call it.

when youre writing

suffix = {"quick" : quick(), "strong" : strong()}

the functions quick() and strong() are getting executed. You'll need to change that to

suffix = {"quick" : quick, "strong" : strong}

and call them as:

suffix["quick"]()

This is a cool feature in python. If you want to pass argumets to your function quick(), you can pass them as

suffix["quick"](<arguments>)

The problem is that you're not storing functions in your dict, but rather the return values of those functions: When you write quick(), you're calling the function. Your dict ends up looking like this:

suffix = {"quick": None, "strong": None}

What you want to do is to store the functions themselves in the dict like so:

suffix = {"quick": quick, "strong": strong}  # no parentheses!

This gives you a dict with two function objects inside. You can now take one of the functions out of the dict and call it:

func = suffix.get("quick")
func()

And just like that, your code will work correctly.

def start():
    suffix = {"quick": quick, "strong": strong}  # no parentheses!
    func = suffix.get("quick")
    func()

start()  # output: dex is 1

If you need to associate some arguments with the functions in the dict, take a look at this question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top