Python3: Calling functions saved as values (strings) in a dictionary
Question: _Background:_

I am reading a python file (.py) that has a number of functions defined and
using a regex to get the names of all the functions and store them in a list.

    
    
    d_fncs = {}
    list_fncs = []
    
    with open('/home/path/somefile.py', 'r') as f:
        for row in f:
            search = re.search(r'def (.*)\(', row)
            if search:                             
                list_fncs.append(search.group(1))
    

The above works fine and as expected returns a list of of the function names
as strings. I have another list which I plan to use as a counter.

    
    
    counter = [str(i) for i in range(1,len(list_fncs)+1)]
    

Finally, I zip the two lists to get a dictionary where the 'keys' are numbers
and the associated 'values' are function names

    
    
    d_fncs = dict(zip(counter,list_fncs))
    

_The problem:_

The intent here is to ask user for an input which would be matched with the
key of this dictionary (counter). Once the key is matched, the function
associated with it is executed. Something like this happens later in the code:

    
    
    def option_to_run(check, option_enter_by_user):
        if check == 'True':
            return (connection(d_fncs[option]))
    
    def connection(fnc):
        conn_name = Connect(some args..) #class imported 
        fnc(conn_name)
    

In this case, as the values from dict are string, I get the following error:

    
    
    File "/home/path/filename.py", line 114, in connection
    
        fnc(conn_name)
    
    TypeError: 'str' object is not callable
    

However, if I manually make a dict and run it then I have no issues and
functions work as expected:

    
    
    d_fncs_expected = {'1': function1, '2': function2, ....}
    

Right now what I am getting is this:

    
    
    d_fncs = {'1': 'function1', '2': 'function2', ....}
    

....what can I do to get the dictionary to work in a way so I can call these
functions? I want the values not to be strings but a type:class


Answer: Replace

    
    
    fnc(conn_name)
    

to

    
    
    eval(fnc)(conn_name) # or eval(fnc(conn_name))
    

**or**

    
    
    globals()[fnc](conn_name)
    

**For example**

    
    
    def myfn(arg):
        print(arg +" is printed")
    d = {1: 'myfn'}
    fun_name = d[1] # 'myfn' 
    
    >>>fun_name("something")
    TypeError: 'str' object is not callable
    >>>eval(fun_name)("something")
    something is printed
    >>>globals()[fun_name]("someting")
    something is printed
    

