Nested Functions
tags: #python/documentation/python_functions
What are nested functions?
A function that is defined within another function is known as a nested function. In Python, this kind of function has direct access and names defined in the enclosing function.
def outer_fucntion()
# can define local variable in the outer function
<statements>
...
def inner function():
# can reference local variables of the outer function
<statements>
...
Note that in a nested function, the inner function is only available from within the outer function. Therefore, if you try to call the inner function, you will get an error.
Access to Local Variables
In nested functions, the inner functions can access variables from the outer function. Whether the variable can be accessed and/or modified depends on whether the variables were declared as local or non-local in the outer function.
Locality with respect to variables, refers to the scope in which the variable can be accessed and used by other parts of the program. This scope defines the region of the code where a variable can be referenced.
If a variable is defined as local in the outer function, the inner function cannot modify its value directly. However, it can access and use the value.
A variable declared within a function is considered a local variable. It is only accessible within that function and cannot be directly accessed from outside the function.
def outer_function():
x = 10 # Local variable in outer function
def inner_function():
print(x) # Accessing the value of x
inner_function()
outer_function()
Access to Non-Local Variables
A variable declared as nonlocal is one that is not local to the current function but is also not a global variable.
If the variable declared in the outer function is non-local, the inner function can both access and modify its value:
def outer_function():
x = 10 # Nonlocal variable in outer function
def inner_function():
nonlocal x
print(x) # Accessing the value of x
x += 5 # Modifying the value of x
inner_function()
print(x) # After the inner function, x has been modified
outer_function()
Access to Global Variables
A variable declared outside any function or explicitly declared as global within a function is a global variable. It can be accessed from any part of the code, including functions.
y = 20 # Global variable
def my_function():
global y # Declaring y as global
print(y)
my_function()