Skip to main content

Introduction to Python Scope

Python Scope

Scope refers to the region of a program where a particular name or identifier is valid and can be accessed.

It determines the visibility and accessibility of variables, functions, and objects within the program.

Python follows a set of rules to define the scope of identifiers, and there are four main levels of scope.

Local Scope

Local scope refers to the innermost level of scope within a function or a code block.

Variables defined within a function or code block have local scope and are accessible only within that specific function or block. Once the function or block is executed, the variables are destroyed and no longer accessible.

As an example:

def my_function():
x = 10 # Local variable within the function
print(x)

my_function() # Output: 10
print(x) # Error: NameError: name 'x' is not defined

In this example:

  • The variable x is defined within the my_function() function and has local scope.
  • It can be accessed and used only within the function.
  • Outside of the function, attempting to access the variable will result in a NameError.

Enclosing (Nonlocal) Scope

Enclosing scope, also known as nonlocal scope, refers to the scope of variables defined in the enclosing function of a nested function.

If a variable is not found in the local scope of a nested function, Python searches for it in the enclosing scope.

As an example:

def outer_function():
x = 10 # Enclosing variable

def inner_function():
print(x) # Accessing the enclosing variable

inner_function() # Output: 10

outer_function()

In this example

  • The variable x is defined in the outer_function() and has enclosing scope.
  • The nested function inner_function() can access and use the variable x from its enclosing scope.

Global Scope

Global scope refers to the outermost level of scope within a Python module or file.

Variables defined outside of any function or class have global scope and can be accessed throughout the module.

Global variables are accessible from any part of the code, including functions and classes.

As an example:

x = 10  # Global variable

def my_function():
print(x) # Accessing the global variable

my_function() # Output: 10

In this example:

  • The variable x is defined outside of any function and has global scope.
  • It can be accessed within the my_function() function.

Built-in Scope

Built-in scope refers to the scope that contains built-in functions, modules, and objects that are available for use without the need for explicit import.

It includes functions like print() and objects like list and dict. Built-in names are accessible from any part of the code.

As an example:

def my_function():
result = max(10, 5) # Accessing the max() function from the built-in scope
print(result)

my_function() # Output: 10

In this example:

  • The max() function is a built-in function, and it can be accessed within the my_function() function without any import statement.