1

I am having difficulty in understanding what it means by returning a function, and what exactly are practical usages of returning functions. Also, for my knowledge, how the below codes work in background.

def f1():
    x = 99
    def f2():
        print(x)
    return f2

f1()

Output:

<function __main__.f1.<locals>.f2()>

now when I use, f1()(), it returns 99. I basically want to understand what happens in background.

def f1():
    x = 99
    def f2():
        print(x)
    return f2

f1()()

Returns 99

prabh
  • 336
  • 1
  • 3
  • 16
  • 3
    functions are objects & first class citizens. They can be created by other functions and called afterwards. Think of lambda for instance. Or UI callbacks passed to widgets & called when clicked – Jean-François Fabre Oct 03 '20 at 10:34
  • 2
    As for practical uses: decorators are typically functions that return functions. – Heike Oct 03 '20 at 10:37
  • 1
    I think that link can help you to understand exactly your question. https://www.learnpython.org/en/Closures#:~:text=Firstly%2C%20a%20Nested%20Function%20is,python%2C%20they%20are%20only%20readonly. – Angerato Oct 03 '20 at 10:39
  • 1
    You might also want to explore the concept of [callable objects](https://stackoverflow.com/questions/111234/what-is-a-callable) in Python. – Jens Oct 03 '20 at 10:41

0 Answers0