How to call Python functions dynamically

If don't want to use globals, vars and don't want make a separate module and/or class to encapsulate functions you want to call dynamically, you can call them as the attributes of the current module:

import sys
...
getattr(sys.modules[__name__], "clean_%s" % fieldname)()

Using global is a very, very, bad way of doing this. You should be doing it this way:

fields = {'name':clean_name,'email':clean_email}

for key in fields:
    fields[key]()

Map your functions to values in a dictionary.

Also using vars()[] is wrong too.


It would be better to have a dictionary of such functions than to look in globals().

The usual approach is to write a class with such functions:

class Cleaner(object):
    def clean_name(self):
        pass

and then use getattr to get access to them:

cleaner = Cleaner()
for f in fields:
    getattr(cleaner, 'clean_%s' % f)()

You could even move further and do something like this:

class Cleaner(object):
    def __init__(self, fields):
        self.fields = fields

    def clean(self):
        for f in self.fields:
            getattr(self, 'clean_%s' % f)()

Then inherit it and declare your clean_<name> methods on an inherited class:

cleaner = Cleaner(['one', 'two'])
cleaner.clean()

Actually this can be extended even further to make it more clean. The first step probably will be adding a check with hasattr() if such method exists in your class.


I have come across this problem twice now, and finally came up with a safe and not ugly solution (in my humble opinion).

RECAP of previous answers:

globals is the hacky, fast & easy method, but you have to be super consistent with your function names, and it can break at runtime if variables get overwritten. Also it's un-pythonic, unsafe, unethical, yadda yadda...

Dictionaries (i.e. string-to-function maps) are safer and easy to use... but it annoys me to no end, that i have to spread dictionary assignments across my file, that are easy to lose track of.

Decorators made the dictionary solution come together for me. Decorators are a pretty way to attach side-effects & transformations to a function definition.

Example time

fields = ['name', 'email', 'address']

# set up our function dictionary
cleaners = {}

# this is a parametered decorator
def add_cleaner(key):
    # this is the actual decorator
    def _add_cleaner(func):
        cleaners[key] = func
        return func
    return _add_cleaner

Whenever you define a cleaner function, add this to the declaration:

@add_cleaner('email')
def email_cleaner(email):
    #do stuff here
    return result
    

The functions are added to the dictionary as soon as their definition is parsed and can be called like this:

cleaned_email = cleaners['email'](some_email)

Alternative proposed by PeterSchorn:

def add_cleaner(func):
    cleaners[func.__name__] = func
    return func

@add_cleaner
def email():
   #clean email

This uses the function name of the cleaner method as its dictionary key. It is more concise, though I think the method names become a little awkward. Pick your favorite.


globals() will give you a dict of the global namespace. From this you can get the function you want:

f = globals()["clean_%s" % field]

Then call it:

f()