Home > Software engineering >  Dictionary of functions declared before the function definitions
Dictionary of functions declared before the function definitions

Time:10-08

I have the following code:

my_dict = {"function1" : function1, "function2" : function2}
def call_functions():
    for key in my_dict.keys():
        mydict[key]()

def function1():
    print "hello 1"

def function2():
    print "hello 2"

if __name__ == '__main__':
    call_functions()
    

My understanding is that this should work - while mydict is being declared before the functions are defined, python is calling them based on a name, not based on an actual pointer to the functions. Since by the time the code is run, they do exist (because this happens through main), there should be no issue. However, I get the dreaded NameError - telling me that function1 doesn't exist.

Short of declaring my_dict at the end of the file (I'd like to keep globals at the top where they're user-accessible), is there a way around this? I don't understand as by the time I call the function, it has been declared

CodePudding user response:

Upon interpreting the first line, the 'function1' and 'function2' variables are referenced but have yet to be declared and so the program crashes as you've seen.

Move the function declarations before the my_dict line and it will work. You also had a typo which I've corrected here. (mydict vs my_dict)

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

def function2():
    print("hello 2")
    
my_dict = {"function1" : function1, "function2" : function2}
def call_functions():
    for key in my_dict.keys():
        my_dict[key]()

if __name__ == '__main__':
    call_functions()

Edit: as @chepner suggested, unless there's something beyond this context that would provide a good reason, keeping the functions in a dictionary is unnecessary where a list would suffice. See example below.

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

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

my_list = {function1, function2}
def call_functions():
    for func in my_list:
        func()

if __name__ == '__main__':
    call_functions()
  • Related