Master Python Scope by the LEGB Rule
Introduction
The variables scope (or namespace) is a very fundamental concept in programming languages. Every developer, no matter which language he or she is using, knows the definition of local and global variables. However, things become a little complicated in Python. Following questions appeared lots of times in interviews for Python developers:
- Why Python needs the
nonlocalkeywords? - What is the LEGB rule?
- Differences between global and nonlocal variables in Python?
- How many types of variables in Python?
- …
This post will explain the Python scope from elementary to profound. After reading, you will totally master this significant concept.
Four Types of Variables and the LEGB Rule
The LEGB rule defines an order in which the Python interpreter retrieves a variable’s name. The four letters represent four types of variables in Python:
- Local Variables (L): Variables in a function
- Enclosed Variables (E): In the context of nested functions (explain later)
- Global Variables (G): The uppermost level variables
- Built-in Variables (B): Variables in Python built-in modules

When a name is called in a program, the correspond variable will be retrieved sequentially in the local, enclosing, global, and built-in scope. If the naming variable exists, then the first occurrence of it will be used. Otherwise, an error will be raised.
Let’s see an example:






