How do I use strings to call functions/methods in Python?

Python Functions are generally called using their name. However, you can also use strings to call functions. For that, use the locals() and globals().

Call functions using strings


In this example, we will learn how to call two functions using strings −

def demo1(): print('Demo Function 1') def demo2(): print('Demo Function 2') locals()['demo1']() globals()['demo2']()


Demo Function 1
Demo Function 2

Call a function using string variable


In this example, we have created a class Example with the function xyzuvw() that accepts arg and print them. The globals() function is used to refer to the class. After that, the getattr() is used to refer to function xyzuvw() within class Example −

class Example: def __init__(self): pass def xyzuvw(self, arg): print('Called xyzuvw({})'.format(arg)) # Using globals() k = globals()['Example']() func = getattr(k, 'xyzuvw') func('demo argument') # Using getarr() getattr(globals()['Example'](), 'xyzuvw')('demo argument')


Called xyzuvw(demo argument)
Called xyzuvw(demo argument)

Updated on: 16-Sep-2022

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started