Python: Scope and the LEGB Rule (Local, Enclosing, Global)
Python scope decides where a variable name is visible and where it is invisible. This post unpacks the LEGB rule (Local, Enclosing, Global, Built-in), the one mental model that explains how Python finds the right variable, plus the two keywords (global and nonlocal) that let you reach across scope lines. Every example below was run on Python 3.14.6. “Namespaces are one honking great idea, let’s do more of those!” Tim Peters, The Zen of Python (PEP 20) Last Updated: July ... Read More
