The scope of a variable in Python determines where in your code that variable is visible and accessible. Python has four general scope levels: local, enclosing, global, and built-in. When searching for a name, Python goes through these scopes in order. It follows the LEGB rule, which stands for Local, Enclosing, Global, and Built-in.

Understanding how Python manages the scope of variables and names is a fundamental skill for you as a Python developer. It helps you avoid unexpected behavior and errors related to name collisions or referencing the wrong variable.

By the end of this tutorial, you’ll understand that:

  • A scope in Python defines where a variable is accessible, following the local, enclosing, global, and built-in (LEGB) rule.
  • A namespace is a dictionary that maps names to objects and determines their scope.
  • The four scope levels—local, enclosing, global, and built-in—each control variable visibility in a specific context.
  • Common scope-related built-in functions include globals() and locals(), which provide access to global and local namespaces.

To get the most out of this tutorial, you should be familiar with Python concepts like variables, functions, inner functions, exception handling, comprehensions, and classes.

Take the Quiz: Test your knowledge with our interactive “Python Scope and the LEGB Rule: Resolving Names in Your Code” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

Python Scope and the LEGB Rule: Resolving Names in Your Code

Test your Python scope skills with this quiz. Practice the LEGB rule, scope vs namespace, globals vs locals, and cases like comprehensions and exceptions.

Understanding the Concept of Scope

In programming, the scope of a name defines the region of a program where you can unambiguously access that name, which could identify a variable, constant, function, class, or any other object. In most cases, you’ll only be able to access a name within its own scope or from an inner or nested scope.

Nearly all programming languages use the concept of scope to avoid name collisions and unpredictable behavior. Most often, you’ll distinguish between two main types of scope:

  1. Global scope: Names in this scope are available to all your code.
  2. Local scope: Names in this scope are only available or visible to the code within the scope.

Scope came about because early programming languages like BASIC only had global names. With this type of name, any part of the program could modify any variable at any time, making large programs difficult to maintain and debug. To work with global names, you’d need to keep all the code in mind to know what value a given name refers to at any time. This is a major side effect of not having scopes and relying solely on global names.

Modern languages, like Python, use the concept of variable scoping to avoid this kind of issue. When you use a language that implements scopes, you won’t be able to access all the names in a program from all locations. Instead, your ability to access a name depends on its scope.

The names in your programs take on the scope of the code block in which you define them. When you can access a name from somewhere in your code, then the name is in scope. If you can’t access the name, then the name is out of scope.

Names and Scopes in Python

Because Python is a dynamically-typed language, its variables come into existence when you first assign them a value. Similarly, functions and classes are available after you define them using def or class, respectively. Finally, modules exist after you import them into your current scope.

You can create names in Python using any of the following operations:

Operation Example
Assignment variable = value
Import import module or from module import name
Function definition def func(): pass
Function argument func(value1, value2,..., valueN)
Class definition class DemoClass: pass

These are all ways to assign a value to either a variable, constant, function, class, instance, or module. In each case, you end up with a name that has a specific scope. This scope will depend on where in your code you’ve defined the name at hand.

Python uses the location of a name definition to associate it with a particular scope. In other words, the place in which you define a name in your code determines the scope or visibility of that name.

For example, if you define a name inside a function, then that name will have a local scope. You can only access the name locally within the function implementation. In contrast, if you define a name at the top level of a module, then that name will have a global scope. You’ll be able to access it from anywhere in your code.

Read the full article at https://realpython.com/python-scope-legb-rule/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]