1

Is there a way to convert a list of function or definition names (strings) into a dictionary based lookup table where the key is the definition name and the value is the definition class that corresponds to the name (the definition name is the name given). It has been said that the safest way is to use the lookup table approach (dictionary mapping) such as here. However, the situation is such that the list of definition names is variable and the user/programmer is not able to directly write it into the code but rather it has to be added programmatically.

So how can I do effective the following:

nameList = ['methodName1','methodName2','methodName3','methodName4'] 
methodLookup = {}
for name in nameList:
        methodLookup.update({name:name.strip('\'')})

Where the dictionary value is the function not the string.

Something similar in essence to but the opposite of the following:

for var, val in dictionary.items(): exec(var + ' = val')
tman
  • 13
  • 3

1 Answers1

1

I guess you could use something like this:

def plus1(x):
    return x + 1
def plus2(x):
    return x + 2

function_list = ['plus1', 'plus2']
function_dict = {function_name: globals()[function_name] for function_name in function_list}

And then after that you can call plus1 function by:

function_dict['plus1'](5)
#6
ExplodingGayFish
  • 2,807
  • 1
  • 5
  • 14
  • Well, that does what I need, thanks. Are globals() safe to use in this way? Some suggest avoiding globals() and locals() if possible. – tman May 25 '20 at 03:29
  • `locals()` only work if you are using it inside a function, in this case you will need to use `globals()`, it should be safe as long as you don't have any other function/variable with the same name – ExplodingGayFish May 25 '20 at 03:37
  • Oops, I just realize that `locals()` not working in this case because we are using `dict` comprehension, so if you change that to a normal `for` loop it will work just fine – ExplodingGayFish May 25 '20 at 03:41