Home > python > call a function by knowing its name as a string

call a function by knowing its name as a string

Problem
I want to call a function but its name is stored in a string. How to do that?

Solution
I wanted to create a menu where the user can select which entry to call. It looks like this:

(1)[r] radio
(2)[ctd] create temp. directory
--------
[m] menu
[q] <

In Python I stored it like this:

menu = OrderedDict()
menu[(1, 'r')] = ('radio', 'apps.radio.radio_player')
menu[(2, 'ctd')] = ('create temp. directory', 'apps.temp_folder.create_temp_folder')

That is, if the user selects “1“, then apps.radio.radio_player() must be called.

Here is the method that can call the appropriate function:

import importlib

def start_app(val):
    """
    Call a function by name (string).
    
    Tip from here: http://stackoverflow.com/questions/3061 .
    """ 
    _, to_call = val
    function_string = to_call # ex.: 'apps.radio.radio_player'
    mod_name, func_name = function_string.rsplit('.', 1)
    mod = importlib.import_module(mod_name)
    func = getattr(mod, func_name)
    func()

The tip is from here.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: