Master Python Scope by the LEGB Rule

Yang Zhou
TechToFreedom
Published in
2 min readNov 2, 2020

--

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 nonlocal keywords?
  • 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…

--

--