[Python] Variable scopes

Rex Chiang
2 min readApr 30, 2023
  • The Python scope concept is generally presented using a rule known as the LEGB rule.
  • LEGB stand for Local, Enclosing, Global, and Built-in scopes.

Local Scope

def func():
s = "Hello"
print(s)

if __name__ == "__main__":
func() # Hello
def func():
s = "Hello"
print(s)

if __name__ == "__main__":
print(s) # NameError : name "s" is not defined
  • Local scope refers to the names which are defined inside the function, and become local variables in this function.
  • These names will only be visible from the block of the function.

Enclosing Scope (Nonlocal Scope)

def outer():
s = "Hello from outer"

def inner():
print(s)

inner()
print(s)

if __name__ == "__main__":
outer() # Hello from outter
# Hello from outter
def outer():
s = "Hello from outer"

def inner():
s = "Hello from inner"
print(s)

inner()
print(s)

if __name__ == "__main__":
outer() # Hello from inner
# Hello from outter
def outer():
s = "Hello from outer"

def inner():
nonlocal s
s = "Hello from inner"
print(s)

inner()
print(s)

if __name__ == "__main__":
outer() # Hello from inner
# Hello from inner
  • Enclosing scope refers to the names which are defined in the nested function, and become enclosing variables in inner and enclosing functions.
  • These names are visible from the code of the inner and enclosing functions.
  • Use nonlocal statement to ask Python to use the enclosing variables instead of creating a local variables, and modify variables defined in the enclosing.

Global Scope

s = "Hello from global"

def func():
print(s)

if __name__ == "__main__":
func() # Hello from global
s = "Hello from global"

def func():
s = "Hello from local"
print(s)

if __name__ == "__main__":
print(s) # Hello from global
func() # Hello from local
print(s) # Hello from global
s = "Hello from global"

def func():
global s
s = "Hello from local"
print(s)

if __name__ == "__main__":
print(s) # Hello from global
func() # Hello from local
print(s) # Hello from local
  • Global scope refers to the names which are defined in the main body of a program, and become global variables in all functions.
  • These names are visible and accessed throughout the program.
  • Use global statement to ask Python to use the globally defined variables instead of creating a local variables, and modify variables defined in the global.

Built-in Scope

def func():
print(True)

if __name__ == "__main__":
func() # True
  • Built-in scopes are the widest scopes that cover all reserved keywords.
  • These names are visible anywhere in the program, without the need to define them.

--

--