Scope and namespaces in Python: where your variables live
You have a variable called counter . You can see it. It's right there. You wrote it yourself, probably after a coffee that stopped being warm twenty minutes ago. You run the program and Python tells you it has no idea what variable you're talking about. Excuse me? Didn't we just see it? Did it leave the building? Do variables have private lives now? Welcome to scope : the part of Python that…
Variables in Python are like residents of different neighborhoods, each with their own space and identity. When you define a variable inside a function, it lives in that function's local scope, like a resident who only exists within the four walls of their home. When the function finishes, the resident moves out, and the variable disappears. However, when you define a variable outside of any function, it lives in the module's global scope, like a permanent resident of the neighborhood.
If you try to modify a global variable from inside a function, Python assumes it's a new local variable and throws an error. To modify a global variable, you need to explicitly tell Python by using the global keyword. This is like sending a letter in advance to inform the postal service that a specific letterbox belongs to a particular resident.
Namespaces are like internal dictionaries where Python stores names and their corresponding objects. Two variables with the same name in different scopes won't overwrite each other because they live in different namespaces. It's like having two folders with the same name in different directories - they are separate and distinct.
The search for a name in Python follows a specific order, LEGB (Local, Enclosing, Global, Built-in). Python starts looking for a name in the local scope of the current function, then moves outward through enclosing scopes, the module's global scope, and finally the built-in names. This is similar to how you might search for a missing item - you start by checking the immediate area and gradually expand your search outward.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.