Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare function from within dictionary

Tags:

python

def mainProgram(myDict):
    methodDict = {'add': addDB(myDict, params[1], params[2]),
                  'find': findDB(myDict, params[1]),
                  'del': removeDB(myDict, params[1], params[2]),
                  'clear': clearAll(myDict)}
    inpt = None
    while inpt != "End":
        inpt = input("-->")
        params = inpt.split()
        methodDict[params[0]]

Here is my code, when I try to execute the code I get, "UnboundLocalError: local variable 'params' referenced before assignment"

Is it possible to do what I am trying to do in python?

like image 640
JPHamlett Avatar asked May 09 '26 10:05

JPHamlett


1 Answers

So, what actually happens at

 methodDict = {'add': addDB(myDict, params[1], params[2]),
              'find': findDB(myDict, params[1]),
              'del': removeDB(myDict, params[1], params[2]),
              'clear': clearAll(myDict)}

is that you execute addDB etc, that is, your methodDict would contain the result of addDB(...params...) if it were to run.

Unfortunately it does not run, as params is not defined when that execution happens.

What you'd want to do is, store a callable in the dictionary and run it... something like

methodDict = {'add': lambda x: addDB(myDict, x[0], x[1])}
# and you execute with
methodDict['add'](params)
like image 167
Tasos Vogiatzoglou Avatar answered May 10 '26 23:05

Tasos Vogiatzoglou