Advertisement
You often create variables, functions, and classes when writing Python code. Each of these has a name that must refer to the right thing. If two parts of your program use the same name, how does Python decide which one you're talking about? That's where namespaces come in.
They help Python keep track of names in different parts of your code so things don't get mixed up. Think of them like labeled containers — each one holds a specific set of names, separate from the others. Once you understand how Python handles these containers, many small bugs and confusion start to clear up.
A namespace is a mapping between names and objects. Behind the scenes, it works like a dictionary: the name is the key, and the object it refers to is the value. When you write total = 5, Python adds an entry in a namespace where the name total now points to the number 5.
Namespaces aren't just one big box. Python separates them based on where and how names are created. If you define a variable inside a function, it lives in a different namespace than one defined at the top of your script. This separation means that two variables with the same name can exist without conflict in different namespaces.
These namespaces help prevent accidental value overwriting and keep parts of your code independent from each other. They also make it easier to trace where something was defined when things go wrong.
Python uses several types of namespaces, each tied to different program parts. They appear at different times during execution and last for different durations.
This is loaded as soon as Python starts. It includes standard functions and constants like print, range, and Exception. These names are always available, even if you don’t define anything yourself.
When a Python script or module runs, Python creates a global namespace. This namespace contains the names of functions, variables, and imported modules defined at the top level. Anything not inside a function or class goes here. In a standalone script, this namespace lasts for the program's life. In an imported module, it sticks around as long as the module is in use.
This appears when you nest one function inside another. The outer function's namespace becomes the enclosing namespace for the inner one. It holds names defined in the outer function but is not accessible globally. The inner function can read these names but can’t change them unless you use a special keyword.
Each time a function is called, Python creates a local namespace. It includes names for arguments and variables defined inside that function. Once the function finishes running, this namespace is removed. This temporary box ensures the function’s activity doesn’t interfere with code elsewhere.
These separate namespaces help Python manage complexity by limiting names to their relevant area.
Python follows a fixed order when trying to resolve a name. This rule is known as LEGB, which stands for Local, Enclosing, Global, and Built-in. The search follows this order step by step until Python finds the name or raises an error.
Here’s an example to see it in action:
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x)
inner()
outer()
Print (x) finds x = "local" first in this code and prints that. If the local assignment were missing, it would print "enclosing." If that were also gone, it would print "global". If none defined x, Python would search for the built-in names.
This predictable order helps avoid surprises. Knowing it allows you to control how values are accessed and prevents you from accidentally hiding a name from a wider scope.
It's easy to confuse scope and namespace, but they're different ideas. A namespace is a container that stores names and their associated objects, while a scope defines where in the code those names can be used.
For example, when you define a variable inside a function, it exists in the local namespace of that function. But its scope is limited to that function. You can’t access it outside, even though it lives in the local namespace while the function runs.
Another example: if you have a nested function, the inner function can access names from the enclosing scope — but only if local ones don't overwrite them. This is how Python handles variable visibility without merging the containers that hold them.
So, while a namespace tells Python where a name belongs, scope tells Python where the name can be used. They work together, but they aren’t the same thing.
Namespaces give structure to how Python handles names. They separate variables and functions into distinct areas, reducing conflict and confusion. Each part of your code — a function, a module, or Python — has its own space to manage names. The LEGB rule defines a clear path for how Python searches for names, making its behavior consistent and predictable. Scope decides where those names can be accessed within different parts of your code. Together, they make programs easier to read, debug, and maintain. Once you get how they work, you'll spend less time guessing where things went wrong and more time building things that work right and efficiently.
Advertisement
Learn the top 7 impacts of the DOJ data rule on enterprises in 2025, including compliance, data privacy, and legal exposure.
Discover how OpenAI's Sora sets a new benchmark for AI video tools, redefining content creation and challenging top competitors
How to fine-tune a Tiny-Llama model using Unsloth in this comprehensive guide. Explore step-by-step instructions on setting up your environment, preparing datasets, and optimizing your AI model for specific tasks
Tech leaders face hurdles in developing reliable AI agents due to complexity, scalability, and integration issues.
NPC-Playground is a 3D experience that lets you engage with LLM-powered NPCs in real-time conversations. See how interactive AI characters are changing virtual worlds
Explore Microsoft Fabric, a unified platform that connects Power BI, Synapse, Data Factory, and more into one seamless data analytics environment for teams and businesses
How to create Instagram Reels using Predis AI in minutes. This step-by-step guide shows how to turn ideas into high-quality Reels with no editing skills needed
Can you really run a 7B parameter language model on your Mac? Learn how Apple made Mistral 7B work with Core ML, why it matters for privacy and performance, and how you can try it yourself in just a few steps
Explore key features, top benefits, and real-world use cases of OpenAI reasoning models that are transforming AI in 2025.
How DeepSeek LLM: China’s Latest Language Model brings strong bilingual fluency and code generation, with an open-source release designed for practical use and long-context tasks
Reddit's new data pricing impacts AI training, developers, and moderators, raising concerns over access, trust, and openness
Gemma 3 mirrors DSLMs in offering higher value than LLMs by being faster, smaller, and more deployment-ready