Python passing function
Passing Functions in Python
In Python, functions are treated as first-class objects, meaning you can pass functions as arguments to other functions and return functions from them. This flexibility makes Python a very powerful programming language, making interactions between functions more convenient and efficient.
Passing Functions as Arguments
First, let’s look at how to pass a function as an argument to another function. This approach allows us to write more flexible code, improves reusability, and improves readability.
def greet(name):
return "Hello, " + name + "!"
def call_func(func, name):
return func(name)
print(call_func(greet, "geek-docs.com"))
In the example above, we define a function called greet
that returns a greeting. Then, we define a function called call_func
that takes another function as an argument and calls it. Finally, we call call_func
, passing it the greet
function and the string “geek-docs.com” as arguments, and print the result.
Running result:
Hello, geek-docs.com!
Returning a function
In addition to passing functions as arguments to other functions, we can also return functions from within a function. This approach is often used to implement advanced techniques such as decorators and closures.
def greet():
def inner(name):
return "Hello, " + name + "!"
return inner
new_func = greet()
print(new_func("geek-docs.com"))
In the above example, we first define a function named greet
, which defines another function named inner
within it and returns the inner
function as its return value. We then call the greet
function, assign the returned function to new_func
, call new_func
, and print the result.
Running result:
Hello, geek-docs.com!
Using Lambda Functions
In addition to using regular functions, we can also use Lambda functions to pass functions. Lambda functions are anonymous functions that are ideal for one-time use.
def call_lambda(func, name):
return func(name)
print(call_lambda(lambda name: "Hello, " + name + "!", "geek-docs.com"))
In the above example, we defined a function named call_lambda
that takes a lambda function as an argument and calls it. We then called call_lambda
, passing it a lambda function as an argument, and printed the result.
Running result:
Hello, geek-docs.com!
Summary
Through this article, we learned how to pass functions as arguments and return functions from functions in Python. This flexibility allows us to write more efficient and concise code, improving code readability and maintainability.