# 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

### Example

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']()


### Output

Demo Function 1
Demo Function 2


## Call a function using string variable

### Example

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')


### Output

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


Advertisements