Passing function as an argument in Python
Last Updated :
14 Aug, 2024
A function can take multiple arguments, these arguments can be objects, variables(of same or different data types) and functions. Python functions are
first class objects. In the example below, a function is assigned to a variable. This assignment doesnât call the function. It takes the function object referenced by shout and creates a second name pointing to it, yell.
Python
# Python program to illustrate functions
# can be treated as objects
def shout(text):
return text.upper()
print(shout('Hello'))
yell = shout
print(yell('Hello'))
Output:
HELLO
HELLO
Higher Order Functions
Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called
higher-order functions
. In the example below, a function greet is created which takes a function as an argument.
Python
# Python program to illustrate functions
# can be passed as arguments to other functions
def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def greet(func):
# storing the function in a variable
greeting = func("Hi, I am created by a function passed as an argument.")
print(greeting)
greet(shout)
greet(whisper)
Output
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, i am created by a function passed as an argument.
Wrapper function
Wrapper function or decorator allows us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it. In Decorators, functions are taken as the argument into another function and then called inside the wrapper function. To know more about decorator
click here. Below is the example of a simple decorator.
Python
# defining a decorator
def hello_decorator(func):
# inner1 is a Wrapper function in
# which the argument is called
# inner function can access the outer local
# functions like in this case "func"
def inner1():
print("Hello, this is before function execution")
# calling the actual function now
# inside the wrapper function.
func()
print("This is after function execution")
return inner1
# defining a function, to be called inside wrapper
def function_to_be_used():
print("This is inside the function !!")
# passing 'function_to_be_used' inside the
# decorator to control its behavior
function_to_be_used = hello_decorator(function_to_be_used)
# calling the function
function_to_be_used()
Output:
Hello, this is before function execution
This is inside the function !!
This is after function execution
Lambda wrapper function
In Python, anonymous function means that a function is without a name. As we already know that
def
keyword is used to define the normal functions and the
lambda
keyword is used to create anonymous functions. This function can have any number of arguments but only one expression, which is evaluated and returned.
Lambda function can also have another function as an argument. The below example shows a basic
lambda function where another lambda function is passed as an argument.
Python3 1==
# Defining lambda function
square = lambda x:x * x
# Defining lambda function
# and passing function as an argument
cube = lambda func:func**3
print("square of 2 is :"+str(square(2)))
print("\nThe cube of "+str(square(2))+" is " +str(cube(square(2))))
Output:
square of 2 is :4
The cube of 4 is 64
Passing function as an argument in Python – FAQs
Can I Pass Functions as Arguments in Python?
Yes, in Python, functions are first-class objects. This means they can be passed as arguments to other functions, returned as values from other functions, and assigned to variables.
How Do You Pass a Function as an Argument?
To pass a function as an argument, simply refer to the function by its name without parentheses. Hereâs a simple example:
def greet(name):
return f"Hello, {name}!"
def farewell(name):
return f"Goodbye, {name}!"
def process_user(callback, name):
print(callback(name))
# Passing functions as arguments
process_user(greet, "Alice")
process_user(farewell, "Bob")
This example demonstrates how a function can be passed as an argument (callback) to another function (process_user) and then executed within that function.
How Do You Pass a Function as an Argument in Python Decorator?
A decorator in Python is a function that takes another function and extends its behavior without explicitly modifying it. Hereâs how to create a decorator that takes a function as an argument:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
# Calling the decorated function
say_hello()
In this example, say_hello() is passed to my_decorator() as the func argument. The wrapper function adds behavior before and after the call to say_hello().
How Do You Declare a Function Passing Argument?
To declare a function that can pass arguments, you define it using the def keyword followed by the function name and parentheses containing the arguments:
def multiply(x, y):
return x * y
# Using the function
result = multiply(5, 3)
print(result) # Output: 15
This function multiply takes two arguments, x and y, and returns their product.
How Many Types of Arguments Are There in Python?
Python supports several types of arguments:
- Positional Arguments: These are arguments that need to be passed in the correct positional order.
- Keyword Arguments: Arguments that are passed to functions using the name of the parameter, regardless of their position.
- Default Arguments: Parameters that assume a default value if a value is not provided in the function call.
- Variable-length Arguments:
- Arbitrary Positional Arguments (
*args): Allows you to pass a variable number of positional arguments. - Arbitrary Keyword Arguments (
**kwargs): Allows for a variable number of keyword arguments.
Example of using various types of arguments:
def func_example(a, b=2, *args, **kwargs):
print(a, b)
print(args)
print(kwargs)
func_example(1, 3, 'extra', another=4)
This example highlights how Python accommodates flexibility in function arguments, making it a robust and versatile language for many programming paradigms.