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()andlocals(), 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.
Get Your Code: Click here to download the free sample code that you’ll use to learn about Python scope and the LEGB rule.
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 CodeTest your Python scope skills with this quiz. Practice the LEGB rule, scope vs namespace, globals vs locals, and cases like comprehensions and exceptions.
Intermediate Python Deep Dive Live Course: Want to see how scope powers closures and decorators? Real Python’s Intermediate Python Deep Dive live course spends a full week on scope, closures, and decorators, with an instructor and a small cohort to work through them with you. Join the waitlist to hear about the next dates.
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:
- Global scope: Names in this scope are available to all your code.
- 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.
Note: In this tutorial, you’ll be using the term name to refer to the identifiers of variables, constants, functions, classes, or any other object that can be assigned a name.
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.
Note: There’s an important difference between assignment operations and reference or access operations. When you assign a name, you’re either creating that name or making it reference a different object. When you reference a name, you’re retrieving the value that the name points to.
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.
Note: If you come from a language like C, C++, or Java, you might expect that any indented block creates its own scope. In Python, that’s not the case. Only functions, classes, and modules introduce a new scope.
Code blocks like if statements, for and while loops, and with statements don’t create a new scope. So, the names you define inside these blocks remain accessible in the enclosing function or module scope once the block finishes executing.
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 ]
