Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How can a Python function return a function?

The following code has two functions as follows

def f2(c, d):
    return c, d
def f1(a, b):
    c = a + 1
    d = b + 2

How can this code be re-worked to make one function return another function?


1 Answer
Rajendra Dharmkar

Python supports first-class functions. In fact, all functions in python are first-class functions.

Python may return functions from functions, store functions in collections such as lists and generally treat them as you would any variable or object.

Defining functions in other functions and returning functions are all possible.

The given code is re-worked as follows. We define functions inside functions and return these.

def f2(c, d):
    return c, d
def f1(a, b):
    c = a + 1
    d = b + 2
    return lambda: f2(c,d)
result = f1(1, 2)
print result
print result()

OUTPUT

C:/Users/TutorialsPoint1/~.py
<function <lambda> at 0x0000000003041CF8>
(2, 4)
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.