Categories
Python Answers

How to pass functions with arguments to another function in Python?

Spread the love

Sometimes, we want to pass functions with arguments to another function in Python.

In this article, we’ll look at how to pass functions with arguments to another function in Python.

How to pass functions with arguments to another function in Python?

To pass functions with arguments to another function in Python, we can create functions that takes a function as an argument.

For instance, we write

def perform(fun, *args):
    fun(*args)

def action1(args):
    # ...

def action2(args):
    # ...

perform(action1)
perform(action2, p)
perform(action3, p, r)

to create the perform function that has the fun function parameter.

And the rest of the parameters we use to call fun with are in the args list.

We use the values in the args list as arguments with *.

Then we call perform as we do in the last 3 lines to call action1 and action2 with the arguments that comes after it.

Conclusion

To pass functions with arguments to another function in Python, we can create functions that takes a function as an argument.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *