Variable scope in Python

  • Post category:python
  • Reading time:5 mins read

In Python, variable scope refers to the region of a program where a particular variable is accessible. It determines where you can access a variable within your code. Python has four levels of variable scope:

  • Local Scope
  • Enclosing Scope – Applied to nested function
  • Global Scope
  • Built-In Scope

Local Scope

Variables defined within a function are considered to have local scope. They can only be accessed within that function. Once the function exits, the variables also cease to exist.

def my_function():
    x = 100
    print("Accessing x locally: ",x)

my_function()
print("Accessing x outside function: ",x)

# Output
Accessing x locally:  100
NameError: name 'x' is not defined

Enclosing (or Nonlocal) Scope

This applies to nested functions. If a variable is not defined in the current local scope but is defined in an enclosing function’s scope, it can be accessed within the inner function.

def outer():
    message = "Hello Proedu!!!"

    def inner():
        # Nested function able to access variable of outer function.
        print(message)

    # Calling inner() function inside outer() function.
    inner()

# Calling outer function.
outer()

# Output
Hello Proedu!!!

Global Scope

Variables defined at the top level of a Python module or explicitly declared as global keyword within a function are considered to have global scope. They can be accessed from anywhere in the module or program.

message = "Hello Proedu!!!"
count = 100

def my_function():
    print("Accessing global variable 'message': ", message)
    print("Accessing global variable 'count': ", count)

my_function()

# Output
Accessing global variable 'message':  Hello Proedu!!!
Accessing global variable 'count':  100

Built-in Scope

This refers to names that are preassigned in Python, such as built-in functions like print(), len(), etc. They are available everywhere in the code.

When a variable is referenced, Python searches for it in the current scope. If not found, it checks the enclosing scopes, then the global scope, and finally the built-in scope. If the variable is not found at all, Python raises a NameError. However, you need to be cautious when using global variables as they can lead to code that is hard to understand and debug.

print(len([1, 2, 3]))

# Output
3

Built-in scope examples in Python include built-in functions, exceptions, and other built-in objects.

# Built-in Functions
print("Hello, Proedu.co!")  # print() is a built-in function
result = len([1, 2, 3, 4])  # len() is a built-in function

# Built-in Exceptions:
try:
    # Some code that may raise an exception
    result = 100 / 0
except ZeroDivisionError as e:
    print("An error occurred:", e)  # ZeroDivisionError is a built-in exception

# Built-in Constants:
print(True)  # True is a built-in constant representing the boolean value True
print(False)  # False is a built-in constant representing the boolean value False

# Built-in Types:
my_list = [1, 2, 3]  # list is a built-in type
my_dict = {"key": "value"}  # dict is a built-in type

# Built-in Methods (associated with built-in types):
my_string = "Hello, Proedu.co!"
print(my_string.upper())  # upper() is a built-in method of the str type

# Built-in Constants in the math module:
import math
print(math.pi)  # pi is a built-in constant in the math module
print(math.e)  # e is a built-in constant in the math module

Built-in names are always accessible without the need for any import statements because they are part of the Python language itself.