Member-only story
LEGB — Variable Scope in Python
Local, Enclose, Global and Build-in
Each programming language has its own variable scope. For python, we could simply follow the LEGB rule that includes
Local, Enclose, Global, and Built-in.
In this article, we will use a few examples to understand their feature and how to access objects of different scopes.
Local; Enclose; Global Variable
We start from this example first
There are three variables with the same name called x, which represent different scopes.
x = 'global var'def outer():
# y is local variable for outer(), enclose variable for inner()
x = 'enclose var'
def inner():
x = 'local var'
print('inner: {}'.format(x))
inner()
print('outer: {}'.format(x))outer()
print(x))
>>>>>>>>>>>>>>>>>>>>>>>>>
inner local var
outer enclose var
global var
Any variable outside a function is a global variable, and a variable inside a function is a local variable. If there is an outer function and an inner function, then the x in the inner function is a local variable, and the x in the outer function is an enclose variable of the internal…










