Pawandeep Singh
Pawandeep Singh

Reputation: 890

Nested Function calling in Python

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

Since f1 is returning f2 so it seems fine when I call f2 as (f1())().

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

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

Can someone explain what is the difference between the function calling of f2 using above 2 ways.

Upvotes: 3

Views: 1064

Answers (1)

Brandon H. Gomes
Brandon H. Gomes

Reputation: 908

The function f2 is local to the scope of function f1. Its name is only valid inside of that function because you defined it there. When you return f2, all you are doing is giving the rest of the program access to the function's properties, not to its name. The function f1 returns something that prints 88 but does not expose the name f2 to the outer scope.

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

Upvotes: 3

Related Questions