I am trying to learn Python and have few doubts with .r.t to multi-level nested functions and function closures in Python. Please help me understand how will this work.
Questions from the code below:
- How can I call func3 from main block ?
- Will func3 have access to x1 from func1 or just x2 from the immediate enclosing scope of func2 ?.
Sample code:
# File: nesteFunc.py
def func1():
x1 = 1
def func2():
x2 = 2
def func3():
x3 = 3
print(x1, x2, x3)
return func3
if __name__ == "__main__":
f = func1()
f() # line 14
The code above gives me this error message:
Traceback (most recent call last):
File "D:/Python Prep/nestedFunc", line 14, in <module>
f()
TypeError: 'NoneType' object is not callable
Process finished with exit code 1
func1does not return a function object, so callingfunc1()will return None to variablef. Andf()raise TypeError.func1putreturn func2then you can dof2 = func1(); f3 = f2(); f3(). Or do something more sane.f, so in the last line you can't call it.