kirakun kirakun - 1 month ago 10
Python Question

Invoking top-level function by name in Python

How can I invoke a top-level function by name? For example,

#!/usr/bin/env python

import sys

def foo():
print 'foo'

def bar():
print 'bar'

# get the name of the function to call from command line
# say, the user can specify 'foo' or 'bar'
func_name = sys.argv[1]

# how do I invoke the function by func_name?
getattr(__main__, func_name) # NameError: global name '__main__' is not defined

Answer

The easiest way is to use globals

globals()[func_name]()

You can also get the current module object by looking it up in sys.modules.

getattr(sys.modules[__name__], func_name)()
Comments