3
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.

asked Jan 13, 2018 at 4:23

1 Answer 1

3

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.

answered Jan 13, 2018 at 4:34
Sign up to request clarification or add additional context in comments.

2 Comments

Yes you are right. So when I call f1() it returns the pointer to f2() function. Which can be verified using : >>> action <function f1.<locals>.f2 at 0x10f28fc80>
Yes, that's correct. Just make sure you refer to the functions by their names only not by func() with parenthesis because this implies calling the function. Note how python stores them as <function f1...> which shows the name without ().

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.