Basic Scoping Rules for Python Variables



In Python, scoping rules define where you can access or modify a variable in your code. It is important to understand these rules because using a variable in the wrong place can cause errors or unexpected results.

Python follows a specific order to find a variable, called the LEGB rule. This rule looks for variables in the following order -

  • Local: First inside the function.
  • Enclosing: Then, in any enclosing function.
  • Global: Then, in the global scope.
  • Built-in: Finally, in Python's built-in names.

What is the LEGB Rule?

The LEGB rule tells Python how to search for variable names in different scopes based on where they are defined -

  • L - Local: These are variables defined inside a function.
  • E - Enclosing: These are variables in the local scope of any enclosing functions (nested functions).
  • G - Global: These are variables defined at the top level of a script or module.
  • B - Built-in: These are the names built into Python, like len, range, print, etc.

Local Scope

In Python, a variable defined inside a function is known as a local variable. It only exists within that function and cannot be accessed from outside.

Example

In the following example, the variable name is created inside the function my_function(), so it belongs to the local scope of that function -

def my_function():
   name = "Alex"
   print(name)

my_function()
# print(name)  # This will raise an error because 'name' is local

This code prints "Alex" when called from within the function, but trying to access the name outside the function will raise a NameError because the variable does not exist in the global scope -

Alex

Global Scope

A variable declared outside of all functions is in the global scope. This means it can be accessed from anywhere in the script, including inside functions, unless a local variable with the same name exists inside a function.

Example

In this example, the variable x is defined outside any function, making it a global variable. The function show() can access x because Python first looks for the variable inside the function (local scope) and, when it doesn't find it, moves to the global scope where x is defined -

x = 10  # Global variable

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

show()

We get the output as shown below -

10

Using Global Keyword

In Python, if you want to modify a global variable from inside a function, you need to use the global keyword. Without it, Python will treat the variable as local and raise an error if you try to change it.

Example

In the following example, the variable count is defined globally. Inside the increase() function, we use the global keyword to tell Python that we want to use and modify the global count instead of creating a new local variable.

As a result, the count is increased by 1, and the updated value is printed -

count = 5  # Global variable

def increase():
   global count   # Tell Python to use the global 'count'
   count += 1     # Modify the global variable

increase()
print(count)

Following is the output of the above code -

6

Enclosing Scope

In Python, an enclosing scope exists when a function is defined inside another function. The inner function can access variables from the outer (enclosing) function, even though those variables are not global.

Example

In the example below, the variable message is defined inside the outer function outer(). The inner function inner() can access this variable because it is part of the enclosing scope.

This is an example of how nested functions in Python can use variables from the function they are enclosed within -

def outer():
   message = "Hello"  # Enclosing variable

   def inner():
      print(message)  # Accessing the variable from the enclosing scope

   inner()

outer()

We get the output as shown below -

Hello

Using "nonlocal" Keyword

The nonlocal keyword in Python is used to modify a variable from the enclosing (outer) function inside a nested function. This allows the inner function to update the value of the variable that belongs to the outer function's scope.

Example

In the following example, the variable num is defined in the outer function. The inner function uses the nonlocal keyword to indicate that it wants to modify the num from the enclosing scope.

As a result, both the inner and outer print statements show the updated value 15 -

def outer():
   num = 10  # Variable in the enclosing scope

   def inner():
      nonlocal num  # Refer to the 'num' in the enclosing function
      num += 5
      print("Inner:", num)

   inner()
   print("Outer:", num)

outer()

After executing the above code, we get the following output -

Inner: 15
Outer: 15

Built-in Scope

Python provides a set of built-in functions and keywords that are always accessible in your code. These built-in names are part of the Python language and are available unless you overwrite them by defining your own variables or functions with the same name.

Example

In the following example, the function len is a built-in function in Python that returns the length of a string.

Since we haven't defined our own len variable, Python uses the built-in version to calculate the length of the string "Python".

If you defined a variable or function with the name len, it would override the built-in function within the current scope -

print(len("Python"))  # Uses the built-in len function

Following is the output obtained -

6

Shadowing Variables

In Python, when a variable is defined both in the local scope (inside a function) and in the global scope (outside of functions), the local variable will "shadow" the global one inside the function.

This means that Python will use the local variable instead of the global one when the function is executed.

Example

In this example, the variable value is defined globally and locally within the show() function. When this function is called, it prints the local value, which shadows the global within the function. However, after the function call, the global value is still accessible -

value = "Global"  # Global variable

def show():
   value = "Local"  # Local variable inside the function
   print(value)

show()
print(value)

We get the result as shown below -

Local
Global

Common Errors

When working with variable scopes in Python, you may come across two common types of errors -

  • NameError - This occurs when you try to use a variable that hasn't been defined in any accessible scope.
  • UnboundLocalError - This happens when you try to use a local variable before assigning it a value, and Python cannot find it in the enclosing scopes either.

Example

In the first function test(), the variable x is printed successfully because it exists in the global scope.

In the second function test_error(), Python raises a NameError because there is no variable named y defined anywhere in the program -

x = 5

def test():
   print(x)  # This works because x is defined in the global scope

test()

def test_error():
   print(y)  # This will raise a NameError because y is not defined anywhere

test_error()

The result obtained is as follows -

5
NameError: name 'y' is not defined
Updated on: 2025-05-12T11:30:20+05:30

458 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements