A nested function (or inner function) is a function defined entirely within the body of another function. Because Python treats functions as first-class objects, a nested function is dynamically created and bound to a new local variable in the enclosing function’s scope each time the outer function is executed.Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
Lexical Scoping and the LEGB Rule
Nested functions rely on Python’s lexical scoping, governed by the LEGB (Local, Enclosing, Global, Built-in) rule for name resolution. When a variable is referenced inside the nested function, Python first checks the nested function’s Local scope. If the variable is not found, it searches the Enclosing scope (the local scope of the outer function). Because of this, the nested function has read-only access to the variables and arguments of its enclosing function by default.Variable Shadowing and the nonlocal Keyword
If you attempt to assign a value to an enclosing scope variable inside the nested function, Python will default to creating a new local variable within the nested function, shadowing the outer variable.
To rebind or modify a variable defined in the enclosing scope, you must explicitly declare the variable using the nonlocal keyword. This instructs the interpreter to bind the identifier to the nearest enclosing scope (excluding the global scope).
Closures and Late Binding
If the outer function returns the nested function object rather than executing it, the nested function retains a reference to the enclosing scope’s environment. This combination of the function and its captured lexical environment is known as a closure. The nested function binds to the variables in the enclosing scope by reference, not by value. This means the nested function will evaluate the enclosing variables at the time the nested function is executed, not at the time it is defined (late binding).Master Python with Deep Grasping Methodology!Learn More





