Everything in Python is an object, even a function or a method. Hence, like variables, Python allows passing functions and methods as arguments.

To pass a function as an argument to another function, write the name of the function without parenthesis in the function call statement (just like what we do with variables) and accept the reference of the function as a parameter in the called function.

def fun2():
    print('This is fun2')
    
def fun1(x):
    print('This is fun1')
    x()

#passing fun2 to fun1
fun1(fun2)
'''
This is fun1
This is fun2
'''

The function that accepts that accepts other function as parameter are know as higher order function.

Similarly, we can also pass a member method to another member methods of the class.

class MyClass:
    def fun2(self):
        print('This is mem-fun2')
        
    def fun1(self, x):
        print('This is mem-fun1')
        x()
        
obj = MyClass()
obj.fun1(obj.fun2)
'''
This is mem-fun1
This is mem-fun2
'''

Pass Function with Arguments

In some cases, the secondary function which we are passing may also need some arguments. In such cases, we can either generate the arguments in the first function or pass them directly along with the reference of the function.

def fun2(arg):
    print('This is fun2 with parmeter value', arg)
        
def fun1(x, arg):
    print('This is fun1')
    x(arg)
    
        
fun1(fun2, 101)
'''
This is mem-fun1
This is fun2 with parmeter value 101
'''

Conlusion

Functions and methods are also objects in Python, what makes them callable is the pre-implementation of the __call__ method in Python source code.

Since functions and methods are also objects in Python, like variables, we can easily pass them as arguments to another function.

Leave a Reply