[PYTHON] Utilization of lambda (when passing a function as an argument of another function)

If you want to pass a function with a different number of arguments as an argument of the same function, you can use it using lambda.

Suppose you have the following sources:


#Argumentless function
def print_type1():
    print('print_Processing type1 ...')
    return '[print_type1]'

def print_com(func):
    print('=== print_Processing com ...===')
    rtn = func()  #When using, there is no argument in the function to pass
    print('{}Was processed.'.format(rtn))
    print()

print_com(print_type1)  #Works fine

You may want to assign a function with arguments to print_com later. Example:

#Function with arguments
def print_type2(day):
    print('print_Processing type2 ...')
    print('day: {}'.format(str(day)))
    return "print_type2"

The following assignment method will fail.

print_com(print_type2)  # →[missing 1 required positional argument: 'day']I get the error"
print_com(print_type2(15))  # →['str' object is not callable]I get the error

So, if you change it to a function with no arguments with lambda and then pass it, it will work.

day = 15
print_com(lambda: print_type2(day))

Alternatively, you can use partial of functools.

from functools import partial
day = 15
print_com(partial(print_type2, day=day))

If you want to solve it by yourself, you can do it by defining the function inside the function.

#Internal function
def print_type3(day):
    def print_type3_inner():
        print('print_Processing type3 ...')
        print('day: {}'.format(str(day)))
        return "print_type3"

    return print_type3_inner

day = 15
print_com(print_type3(day))

lambda01.py


from functools import partial

#Argumentless function
def print_type1():
    print('print_Processing type1 ...')
    return '[print_type1]'


def print_com(func):
    print('=== print_Processing com ...===')
    rtn = func()  #When using, there is no argument in the function to pass
    print('{}Was processed.'.format(rtn))
    print()


#Function with arguments
def print_type2(day):
    print('print_Processing type2 ...')
    print('day: {}'.format(str(day)))
    return "print_type2"


#Internal function
def print_type3(day):
    def print_type3_inner():
        print('print_Processing type3 ...')
        print('day: {}'.format(str(day)))
        return "print_type3"

    return print_type3_inner


print_com(print_type1)  #Works fine

#↓ Such an assignment method will fail
# print_com(print_type2)  # →[missing 1 required positional argument: 'day']I get the error

# print_com(print_type2(15))  # →['str' object is not callable]I get the error

#If you change it to a function with no arguments with lambda and then pass it, it will work.
day = 15
print_com(lambda: print_type2(day))

#Or
day += 1
print_com(partial(print_type2, day=day))

day += 1
print_com(print_type3(day))

Execution result === Processing print_com ... === Processing print_type1 ... Processed [print_type1].

=== Processing print_com ... === Processing print_type2 ... day: 15 Processed print_type2.

=== Processing print_com ... === Processing print_type2 ... day: 16 Processed print_type2.

=== Processing print_com ... === Processing print_type3 ... day: 17 Processed print_type3.

Recommended Posts

Utilization of lambda (when passing a function as an argument of another function)
Format when passing a long string as an argument of python
A simple difference when passing a pointer as a function argument
Python> function> Example of taking function as an argument> map (lambda x: 2 ** x, [1, 2, 3]) / locals () ['myprint'] (3.1415, 2.718)
Note: The meaning of specifying only * (asterisk) as an argument in the Python function definition.
Don't take an instance of a Python exception class directly as an argument to the exception class!
Check the argument type annotation when executing a function in Python and make an error
The story I was addicted to when I specified nil as a function argument in Go
Try adding a simple image baking function as an add-on
Precautions when using a list or dictionary as the default argument
If you give a list with the default argument of the function ...
[Fabric] I was addicted to using boolean as an argument, so make a note of the countermeasures.
The story of making a tool to load an image with Python ⇒ save it as another name
[python] Callback function (pass function as argument)
[Python] Make the function a lambda function
The eval () function that calculates a string as an expression in python
[PyTorch] Why you can treat an instance of CrossEntropyLoss () like a function
Do not specify a mutable object (list type, dictionary type, etc.) as the initial value of the function argument of python.