2

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?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Mario
  • 921
  • 2
  • 10
  • 22

4 Answers4

3

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()
Alexander Zhukov
  • 4,357
  • 1
  • 20
  • 31
2

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.
falsetru
  • 357,413
  • 63
  • 732
  • 636
2

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>)
Ashoka Lella
  • 6,631
  • 1
  • 30
  • 39
2

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.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149