pulsefrequency
pulsefrequency

Reputation: 13

python: calling a function from a dictionary in another module

I have an if statement that checks a dictionary from another module to see if it contains a keyword that happens to have a function as its value. The function is never explicitly called but it executes when the program initiates before anything else even happens. This is not the desired behavior, the function should never actually be called. If the keyword is in the dictionary, all that should happen is the program prints 'good' to the terminal. Am I doing something wrong? I've been scouring the internet for hours and my brain hurts :(

From 'source.py':

import commands
game_state = 'playing'

while game_state == 'playing':
    player_input = raw_input('>>')
    if player_input == 'quit':
        break 
    elif player_input in commands.command_list:
        print 'good' 

And from 'commands.py':

def one():
    print '1'
command_list = {'one' : one()}

And finally, here is the resulting terminal after inputting the function name:

1
>>one
good
>>_

The '1' at the very beginning shouldn't be there, as the function is never actually called... right? I can't figure this out

Upvotes: 1

Views: 758

Answers (1)

shx2
shx2

Reputation: 64328

You store the value returned by a call to one in your dict. Since your dict is global, it gets its value at import-time. I.e. your code is equivalent to:

x = one()  # call the function
command_list = {'one' : x}  # store result in a dict

Try:

command_list = {'one' : one}  # store the function in a dict

This stores the function object, without calling it.

Upvotes: 2

Related Questions