Pass function as an argument in Python
In Python a function is an object, just like a number or a string. So you can store a function in a variable, pass it to another function as an argument, and even return it from a function. A function that takes another function as an argument is called a higher order function.
Functions are objects
You can give a function another name by assigning it to a variable. Notice that we write the function name without brackets, because brackets would call it.
def display(text):
return text.upper()
print(display("Hello"))
show = display
print(show("Hello"))
HELLO
HELLO
Pass a function to another function
Here the function meet() takes a function as its argument and calls it.
def show(text):
return text.upper()
def display(text):
return text.lower()
def meet(func):
greeting = func("This is created by a function passed as an argument.")
print(greeting)
meet(show)
meet(display)
THIS IS CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
this is created by a function passed as an argument.
Same meet() gives different results, depending on which function we give it.
More examples
def apply(func, value):
return func(value)
print(apply(len, "python"))
print(apply(str.upper, "python"))
def apply_twice(func, x):
return func(func(x))
print(apply_twice(lambda n: n * 2, 3))
6
PYTHON
12
The built-in functions sorted(), map() and filter() are higher order functions too. For example, sorted(words, key=len) sorts the words by their length.
words = ["banana", "fig", "apple"]
print(sorted(words, key=len))
['fig', 'apple', 'banana']
Return a function from a function
A function can also create and return another function. This idea is used in closures and decorators.
Summary
- Functions are objects, so they can be stored in variables and passed around.
- Pass the function name without brackets.
- A function that takes or returns another function is a higher order function.
- Related: lambda and closures.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |