What Are Namespaces in Python and Why Do They Matter?
Learn what namespaces are in Python, how the LEGB scope resolution rule works step by step, and how the global and nonlocal keywords affect variable scope.
Expected Interview Answer
A namespace is a mapping from names to objects, essentially a container that keeps identifiers like variables and functions unique within a given scope, preventing naming collisions across different parts of a program.
Python maintains several namespaces at once: the built-in namespace (things like len and print), the global namespace of a module, and the local namespace inside a function, and it resolves a name using the LEGB rule — Local, Enclosing, Global, then Built-in — searching in that order until a match is found. Each function call creates its own fresh local namespace, modules each get their own global namespace, and classes get a namespace for their attributes, which is why the same name `x` can mean different things in different scopes without conflict.
- Prevents naming collisions between unrelated parts of a program
- Enables the same name to be reused safely in different scopes
- Underpins how imports, functions, and classes stay organized
- The LEGB rule gives predictable, debuggable name resolution
- Supports tools like globals() and locals() for introspection
AI Mentor Explanation
A namespace is like each club maintaining its own separate player registry, so a name like 'Sam' on one club's roster never conflicts with a different 'Sam' on another club's roster even in the same league. When a selector looks for a player, they check the current squad's list first, then the league's shared list, mirroring how Python searches local scope before falling back to wider ones.
Step-by-Step Explanation
Step 1
Built-in namespace
Contains names like len, print, and str, always available without importing anything.
Step 2
Global namespace
Each module has its own global namespace holding top-level names defined in that file.
Step 3
Local namespace
Each function call creates a fresh local namespace for its parameters and local variables.
Step 4
LEGB resolution order
Python looks up a name in Local, then Enclosing, then Global, then Built-in scope, stopping at the first match.
Step 5
Introspection tools
globals() and locals() return dictionaries representing the current global/local namespaces.
What Interviewer Expects
- Defines a namespace as a name-to-object mapping
- Names the LEGB scope resolution order correctly
- Explains why the same variable name can exist safely in different scopes
- Distinguishes global namespace (per module) from local (per function call)
- Mentions globals()/locals() for introspection
Common Mistakes
- Confusing namespace with a specific data structure like a dict (it's the concept, dicts often implement it)
- Getting the LEGB order wrong or forgetting the Enclosing scope for nested functions
- Assuming a global keyword is needed to just read a global variable (only needed to assign)
- Thinking Python has block-level scoping like some other languages (it doesn't for if/for blocks)
Best Answer (HR Friendly)
“A namespace is how Python keeps names like variables and functions organized so the same name can be reused in different parts of a program without clashing, similar to how two different companies can each have their own employee named 'Alex' without confusion.”
Code Example
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x) # local
inner()
print(x) # enclosing
outer()
print(x) # global
print(len("built-in lookup works everywhere"))Follow-up Questions
- What is the LEGB rule and how does Python apply it?
- When is the `global` keyword required inside a function?
- What is the `nonlocal` keyword used for?
- How do globals() and locals() differ?
- Does Python have block-level scoping for if/for statements?
MCQ Practice
1. What is a namespace?
A namespace is essentially a lookup table mapping identifiers (names) to the objects they refer to.
2. What is the correct LEGB order?
Python resolves names by checking Local, then Enclosing, then Global, then Built-in scope, in that order.
3. When must you use the `global` keyword inside a function?
Reading a global variable works without the keyword, but assigning to it inside a function requires declaring it global first.
Flash Cards
What is a namespace? — A mapping from names (identifiers) to the objects they reference.
What does LEGB stand for? — Local, Enclosing, Global, Built-in — Python's name resolution order.
When is `global` required? — Only when assigning to a global variable from inside a function, not when reading it.
What does `nonlocal` do? — Lets a nested function assign to a variable in its enclosing (non-global) scope.