blog posts

How To Pass Function As Argument In Python?

How To Pass Function As Argument In Python?

https://en.wikipedia.org/wiki/ASCIIIn Python, A Function Can Receive Multiple Arguments. These Arguments Can Be Objects, Variables (Of The Same Or Different Data Types), And Functions. 

Python functions are first-class objects, and for this reason, they provide good functionality to developers, one of which is passing the function as an argument, which we will learn how to do in this article.

Pass function as an argument.

Suppose we have a list of strings representing the names of fruits:

>>> fruits = [‘kumquat’, ‘cherimoya’, ‘Loquat’, ‘longan’, ‘jujube’]

If we want to sort this list alphabetically, we can pass it to the built-in sort function:

>>> sorted(fruits)

[‘Loquat’, ‘cherimoya’, ‘jujube’, ‘kumquat’, ‘longan’]

As you can see, the sorting is not strictly alphabetical because when Python sorts strings, it puts all uppercase letters before all lowercase letters due to the structure of the Unicode and ASCII encoding systems. We can solve this problem by providing a key argument to the built-in sorter function.

>>> help(sorted)

sorted(iterable, /, *, key=None, reverse=False)

This key argument should be a function with each item in the fruit list to sort all the elements according to what we want.

In the example above, we can create a function that lowers the letters of any given string so that the sorting process is based on lowercase letters.

>>> def lowercase(string):

…     return string.lower()

To sort by lowercase strings, we call the sorter with a key argument that points to this lowercase function:

>>> sorted(fruits, key=lowercase)

[‘cherimoya’, ‘jujube’, ‘kumquat’, ‘longan’, ‘Loquat’]

This will correctly sort our list of strings alphabetically while preserving the original letter combinations.

Note that when we call the sorter function, we didn’t put the parentheses (()) after the lowercase letters to call it, and we used the following calling pattern:

>>> lowercase(‘X’)

‘x’

As you can see, we have not reduced the characters of the string in any way, and we only mentioned the lowercase letters:

>>> lowercase

<function lowercase at 0x7fc8a3fc09d0>

We passed the lowercase function object to the sorter function via its key argument:

>>> sorted(fruits, key=lowercase)

The above example shows that Python allows us to pass functions as arguments to other functions. o that the sorter function can repeatedly call itself on each unique item in the lowercase fruit list, optimizing the sorting process by using the return value as a comparison key. To better understand the issue, let us refer to other models. Please do it.

Another example of assigning a function to a variable as an object

In the following example, a function is assigned to a variable; of course, the procedure is not called in the above allocation process. Instead, the object of the mentioned function is received by shoutout and delivered to the yell variable. Finally, the input parameter is entered in the yell print command. Receives pass it to the function to print the word hello in capital letters.

# Python program to illustrate functions

# can be treated as objects

def shout(text):

return text.upper()

 

print(shout(‘Hello’))

 

yell = shout

 

print(yell(‘Hello’))

Higher Order Functions

Since functions are objects, we can pass them as arguments to other functions. Functions that can accept other functions as arguments are called higher-order functions. In the following example, a function called greet is created, which receives a function as an argument.

# 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)

In the code above, the shout function is defined, which receives a string variable as input, converts it to uppercase letters, and returns it as the function’s return value.

Next, a second function called whisper is defined, which also receives a string variable, but converts it to lowercase letters and returns it as the function’s return value.

The third function is called greet, defined as receiving parts as arguments. This function has an idea called func. This variable can receive two parts as arguments. As we mentioned, functions in Python are of object type, so the func variable is not a problem in this context. Next, a variable called greeting is defined that receives the return value of the func function, which is of string type. Next, the print command prints the greeting value.

The last two lines of the above code receive the shout and whisper functions as variables, respectively. As you can see, defining and calling the function in Python is more straightforward than you imagine.

The output of the above code snippet prints the string in uppercase and then lowercase.

Wrapper function

The wrapper function or decorator allows us to extend the functionality of another function without changing its structure. In the working mechanism of decorators, functions are sent as arguments to another function, and the calling process is done in the wrapper function. Below is an example of a simple decorator.

# 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 the 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()

The output of the above code snippet is as follows:

 

Hello, this is before the function execution.

This is inside the function !!

This is after function execution.

Lambda wrapper function

In Python, an anonymous function means that a function has no name. In Python, the def keyword defines normal functions, and the lambda keyword is used to create anonymous functions. This function can take any number of arguments but can only accept an expression that will be evaluated and returned. The lambda function can accept another function as an argument. The following example shows an essential lambda function that passes another lambda function as an argument.

# 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))))

The output of the above code snippet is as follows:

Square of 2 is:4

The cube of 4 is 64

last word

Python allows us to call functions most simply and send one or more arguments as parameters to other functions. As you have seen, in Python, you can pass functions as arguments to other functions; this is possible thanks to the object-oriented nature of functions. Also, if you pay attention to the first example, this technique allows us to use a particular type of recursive function construction mechanism in an advanced way.