Variable Scope in Python

Vivekawasthi
Python in Plain English
3 min readJul 6, 2022

--

The part of a program where a variable is accessible is called its scope. There are four major types of variable scope and this is the basis for the LEGB rule. LEGB stands for Local -> Enclosing -> Global -> Built-in.

Local Scope

Whenever you define a variable within a function, its scope lies ONLY within the function. It is accessible from the point at which it is defined until the end of the function and exists for as long as the function is executing. Which means its value cannot be changed or even accessed from outside the function.

def print_local():
local_num = 1
print("The number defined is: ", local_num)

print_local()
Output -
The number defined is: 1

Enclosing Scope

We have a nested function (a function defined inside another function). How does the scope change? Let’s see with the help of an example.

def outer():
num = 1
def inner():
second_num = 2
# Print statement 1 - Scope: Inner
print("first_num from outer: ", num)
# Print statement 2 - Scope: Inner
print("second_num from inner: ", second_num)
inner()
# Print statement 3 - Scope: Outer
print("second_num from inner: ", second_num)

outer()
Output-
first_num from outer: 1
second_num from inner: 2
Traceback (most recent call last):
File "C:/Users/", line 13, in <module>
outer()
File "C:/Users/", line 11, in outer
print("second_num from inner: ", second_num)
NameError: name 'second_num' is not defined

Got an error? This is because you cannot access second_num from outer(). It is not defined within that function. However, you can access num from inner() , because the scope of num is larger, it is within outer().
This is an enclosing scope. Outer's variables have a larger scope and can be accessed from the enclosed function inner().

Global Scope

Whenever a variable is defined outside any function, it becomes a global variable, and its scope is anywhere within the program.

num = 1
def outer():
print(num)

outer()
Output-
1

Built-in Scope

All the special reserved keywords fall under this scope. We can call the keywords anywhere within our program without having to define them before use.

To find Keywords in Python, Import Built Ins

import builtins

print(dir(builtins))
Output-
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord. Interested in Growth Hacking? Check out Circuit.

--

--