A namespace in Python maps names to objects. Python has four kinds: built-in, global (module), enclosing and local. Scope decides which of these namespaces Python searches when your code uses a name, following the LEGB rule. This page explains both ideas, fixes the code samples above and shows the global and nonlocal keywords with runnable examples and their expected output.
What is Namespace in Python?
A namespace is a collection of currently defined symbolic names along with information about the object that each name references. You can think of a namespace as a dictionary in which the keys are the object names and the values are the objects themselves. Each key-value pair maps a name to its corresponding object.
Types of Namespace

Scope in Namespace in Python

Use of Types of Namespaces?

Example Code of Namespace Types



Video of Namespace of Python
The four namespaces and how long they live
The images above list the namespace types. The table below sets out when each one is created and when it goes away. The lifetime matters because a name only exists while its namespace exists.
| Namespace | What it holds | Created | Destroyed |
|---|---|---|---|
| Built-in | print, len, range, Exception and other built-ins | When the interpreter starts | When the interpreter exits |
| Global (module) | Names defined at the top level of a module or script | When the module is imported or the script runs | Usually when the interpreter exits |
| Enclosing | Local names of an outer function, as seen by a nested function | When the outer function is called | When the outer function returns, unless a closure keeps a reference |
| Local | Parameters and names assigned inside a function | When the function is called | When the function returns or raises |
Note: "Global" in Python means module-level. Each module has its own global namespace, so a variable named config in app.py and another named config in utils.py do not clash.
How Python resolves a name: the LEGB rule
When code reads a name, Python searches the namespaces in a fixed order: Local, then Enclosing, then Global, then Built-in. It stops at the first match. If no namespace contains the name, it raises NameError. The example below defines the same name at three levels so you can see which one wins at each point.
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print("inner sees:", x)
inner()
print("outer sees:", x)
outer()
print("module sees:", x)
print("built-in found:", len)Code language: PHP (php)
inner sees: local
outer sees: enclosing
module sees: global
built-in found: <built-in function len>Code language: JavaScript (javascript)
Each x lives in a separate namespace, so assigning one never overwrites another. len is not defined anywhere in the file, so the search falls through to the built-in namespace.
Note: Class bodies are not part of the enclosing scope for the methods inside them. A method has to use self.attr or ClassName.attr to reach class attributes. List, dict and set comprehensions also have their own local scope, so their loop variable does not leak into the surrounding code.
Inspecting namespaces in code
The idea above that a namespace works like a dictionary is literally true for module namespaces. You can look at namespaces at runtime with a few built-ins:
import builtins
x = 10
def show():
y = 20
print("locals:", locals())
show()
print("x in globals:", "x" in globals())
print("globals()['x']:", globals()["x"])
print("len is built-in:", "len" in dir(builtins))Code language: PHP (php)
locals: {'y': 20}
x in globals: True
globals()['x']: 10
len is built-in: TrueCode language: PHP (php)
globals()returns the module's real namespace dictionary.locals()inside a function returns a snapshot of the local names. Writing to that dictionary does not change the function's variables.dir(builtins)lists everything in the built-in namespace.vars(obj)returns the__dict__of a module, class or instance, which is that object's attribute namespace.
Changing outer variables with global and nonlocal
Reading a name from an outer scope needs no keyword. Assigning to it does. Any assignment inside a function makes that name local to the whole function, unless you declare it first. namespace2.py above uses global to update a module-level variable and prints 6. To update a variable of an enclosing function, use nonlocal:
def make_counter():
count = 0
def increment():
nonlocal count # rebind count in make_counter's namespace
count += 1
return count
return increment
counter = make_counter()
print(counter()) # 1
print(counter()) # 2
print(counter()) # 3Code language: PHP (php)
count outlives the make_counter() call because the returned increment function, a closure, keeps a reference to the enclosing namespace. nonlocal only searches enclosing function scopes. It never reaches module globals, and Python raises a SyntaxError if no enclosing function defines the name.
Corrected versions of the gist examples
The three gist files above have some problems. namespace1.py defines a nested function that is never called and mixes tabs with spaces. A comment in it gets the global rule wrong. namespace3.py crashes on purpose, but nothing tells the reader that. Here is a runnable version of namespace1.py that uses 4-space indentation as PEP 8 recommends:
var1 = 5 # global namespace
def some_func():
var2 = 6 # local namespace of some_func
def some_inner_func():
var3 = 7 # local namespace of some_inner_func
# var2 is found in the enclosing scope, var1 in the global scope
print(var1, var2, var3)
some_inner_func()
some_func() # prints: 5 6 7Code language: PHP (php)
The comment in namespace1.py says that count = count + 1 uses the global variable without a global declaration. That is wrong. Without global count, both count = count + 1 and count = 1 make count local. The first form then fails because it reads the local before giving it a value:
count = 5
def broken():
count = count + 1 # count is local here, so reading it fails
broken()
# UnboundLocalError: cannot access local variable 'count' where it is not associated with a valueCode language: PHP (php)
Older Python versions word this error as local variable 'count' referenced before assignment. Either way, the fix is global count, as namespace2.py shows. namespace3.py prints two lines and then fails:
Inside some_func
Inside inner function, value of var: 10
Traceback (most recent call last):
...
NameError: name 'var' is not definedCode language: JavaScript (javascript)
An outer function cannot see the locals of an inner function, because the LEGB search only goes outward. If the outer function needs the value, return it:
def some_func():
print("Inside some_func")
def some_inner_func():
var = 10
print("Inside inner function, value of var:", var)
return var
var = some_inner_func()
print("Value of var in outer function:", var)
some_func()Code language: PHP (php)
Common namespace errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
UnboundLocalError on a variable that exists globally | The function assigns to the name, which makes it local everywhere in that function | Add global name or nonlocal name, or better, pass the value in and return the result |
NameError: name 'x' is not defined | The name is not in the local, enclosing, global or built-in namespace, often because it was defined in an inner function | Return the value, or define it in a scope that encloses the code that uses it |
TypeError: 'list' object is not callable | A variable named list (or str, id, input) hides the built-in | Rename the variable. In an interactive session, del list brings the built-in back |
SyntaxError: no binding for nonlocal 'x' found | nonlocal was used for a name that only exists globally, or does not exist | Use global for module variables, or define the name in the enclosing function |
Best practices
- Pass values in as arguments and return results instead of changing globals. Functions are then easier to test and to reason about.
- Keep module-level names for constants (
MAX_RETRIES = 3) and configuration, and write constants in upper case. - Do not name variables after built-ins such as
list,dict,id,typeorinput. - Use
nonlocalmainly in closures and decorators that need to keep state. For anything bigger, a class is usually clearer. - Prefer
import moduleoverfrom module import *. A wildcard import fills your global namespace with names you cannot see in the code.
Frequently asked questions
What is the difference between a namespace and a scope in Python?
A namespace is the mapping of names to objects, such as a module's global names. A scope is the region of code where a namespace can be accessed directly without a prefix. The LEGB rule sets the order in which scopes are searched.
What does LEGB stand for in Python?
Local, Enclosing, Global, Built-in. When code uses a name, Python searches these namespaces in that order and uses the first match.
When should I use global versus nonlocal?
Use global to assign to a module-level variable from inside a function. Use nonlocal to assign to a variable of an enclosing function from inside a nested function. Neither keyword is needed if you only read the variable.
Are global variables shared between Python modules?
No. Each module has its own global namespace. To use another module's variable, import the module and refer to it as module.name.
Why do I get UnboundLocalError when the variable exists globally?
Assigning to a name anywhere in a function makes it local to the whole function. Reading it before that assignment therefore fails. Declare it with global, or pass the value in as an argument.
Related tutorials
- More Python tutorials
- TOP 100+ INTERVIEW QUESTIONS FOR PYTHON:-
- Top 50 Python Interview Questions and Answers
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals