Python – Nested function calls in Python

Nested function calls in Python… here is a solution to the problem.

Nested function calls in Python

def f1(): 
    X = 88
    def f2(): 
        print(X)
    return f2
action = f1() 
action()

Since f1 is returning f2,

it seems fine when I call f2 as (f1())().

But when I call f2 directly as f2(), it gives an error.

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'f2' is not defined

Can someone explain the difference between calling the f2 function in the above two ways?

Solution

The f2 function is the range of the local function f1. Its name is valid only inside the function because you defined it there. When you return to F2, all you do is give the rest of the program access to the function’s properties, not its name. Function f1 returns the contents of print 88 but does not expose the name f2 to the outer scope.

Calling f2 indirectly via f1()() or action() is perfectly valid because these names are defined in that outer scope. The name f2 is not defined in the outer scope, so calling it is a NameError.

Related Problems and Solutions