Example 1- Calling an Inner function
Input
x = 500
def check_func(): ---Local Scope
x = 250
def check_again_func():
x = 550
print(x)
check_again_func()
Output
550
Example 1.2 ---Enclosing Scope
Input
x = 500
def check_func():
x = 250
def check_again_func():
print(x)
check_again_func()
Output
250
Example #2.1 Inner and Outer function have a variable
x=500
def check_func():
x=777
def check_again_func():
x=550
print(x)
check_again_func()
print(x)
Output
550
777
Example 2.2 Only Inner function has a variable
Input
x=500
def check_func():
def check_again_func():
x=550
print(x)
check_again_func()
print(x)
Output
550
500
Example #2.3 Inner Function has a global variable but outer function has a local variable, Local scope overrules Global variable in a function call
Input
x=500
def check_func():
x=777
def check_again_func():
global x
x=550
print(x)
check_again_func()
print(x)
Output
550
777
Example 2.4 Outer function has no local variable and inner function updates the global variable.
Input
x=500
def check_func():
def check_again_func():
global x
x=550
print(x)
check_again_func()
print(x)
Output
550
In the example 1, I am calling the inner function check_again_func() and that basically returns output based on Local scope in 1 and Enclosing Scope in 1.2.
In the example 2, I wanted to check how the outer function reacts to LEGB rule, based on all the example from 2 and onwards, I concluded:
- Inner function local variable is not local to the outer function
- Inner function enclosing variable does not apply to the outer function
- Inner function global keyword apply to the outer function only when the local variable is not present in the outer function to overrule it.
Am I understanding this correct? Please let me know