accessing callable objects using strings

Ever thought of how to access functions given some string of the same name?

Here’s a simple code snippet to do the same. This is based on code from NMMA

Let’s say, for example you have functions MyFunc1 and MyFunc2 in a file functions.py and you wish to use the function based on a user input which can be either "MyFunc1", "MyFunc2" or some other invalid value.

Your functions.py may look something like this

def MyFunc1():
    print("Hi, I am MyFunc1")
def MyFunc2():
    print("Hi, I am MyFunc2")

Now you can access these functions using strings as such:

import inspect
import functions as func

MY_FUNCTIONS = { k: v for k, v in func.__dict__.items() if inspect.isfunction(v) }

function1 = MY_FUNCTIONS["MyFunc1"]
function2 = MY_FUNCTIONS["MyFunc2"]
function1()
>>> Hi, I am MyFunc1
function2()
>>> Hi, I am MyFunc2
function3 = MY_FUNCTIONS["MyFunc3"]
>>> Traceback (most recent call last):
>>>     File "main.py", line 12, in <module>
>>>         function3 = MY_FUNCTIONS["MyFunc3"]
>>> KeyError: 'MyFunc3'



Enjoy Reading This Article?

Here are some more articles you might like to read next:

  • Custom cursor
  • zsh plugins on non-root servers