How do I use a variable as a function name in python
Question: How do I use a variable as a function name so that I can have a list of
functions and initialize them in a loop. I'm getting the error I expected
which is str object is not callable. But I don't know how to fix it. Thanks.

    
    
    #Open protocol configuration file
    config = configparser.ConfigParser()
    config.read("protocol.config")
    
    # Create new threads for each protocol that is configured
    protocols = ["ISO", "CMT", "ASCII"]
    threads = []
    threadID = 0
    
    for protocol in protocols:
            if (config.getboolean(protocol, "configured") == True):
                    threadID = threadID + 1
                    function_name = config.get(protocol, "protocol_func")
                    threads.append(function_name(threadID, config.get(protocol, "port")))
    
    # Start new threads
    for thread in threads:
            thread.start()
    
    print ("Exiting Main Protocol Manager Thread")
    


Answer: If you put your set of valid `protocol_func`s in a specific module, you can
use `getattr()` to retrieve from that module:

    
    
    import protocol_funcs
    
    protocol_func = getattr(protocol_funcs, function_name)
    threads.append(protocol_func(threadID, config.get(protocol, "port")))
    

* * *

Another approach is a decorator to register options:

    
    
    protocol_funcs = {}
    
    def protocol_func(f):
      protocol_funcs[f.__name__] = f
      return f
    

...thereafter:

    
    
    @protocol_func
    def some_protocol_func(id, port):
      pass # TODO: provide a protocol function here
    

That way only functions decorated with `@protocol_func` can be used in the
config file, and the contents of that dictionary can be trivially iterated
over.

