MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Python Tutorials: Namesapce in Python with example

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

Nested circles showing local namespace inside global namespace inside built-in namespace

Scope in Namespace in Python

Diagram of nested Python scopes: built-in, module global, class and method; lower names override higher ones

Use of Types of Namespaces?

Python namespace types: built-in, global, local and enclosing, with when each is created and how long it exists

Example Code of Namespace Types

Python code labelling x = 1 as a global variable and x, y in a function and loop as local variables
Python discounter closure with variables highlighted as local, enclosing, global and built-in names
Python nested functions boxed as global, enclosing and local scopes, with the printed output

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.

NamespaceWhat it holdsCreatedDestroyed
Built-inprint, len, range, Exception and other built-insWhen the interpreter startsWhen the interpreter exits
Global (module)Names defined at the top level of a module or scriptWhen the module is imported or the script runsUsually when the interpreter exits
EnclosingLocal names of an outer function, as seen by a nested functionWhen the outer function is calledWhen the outer function returns, unless a closure keeps a reference
LocalParameters and names assigned inside a functionWhen the function is calledWhen 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

SymptomCauseFix
UnboundLocalError on a variable that exists globallyThe function assigns to the name, which makes it local everywhere in that functionAdd global name or nonlocal name, or better, pass the value in and return the result
NameError: name 'x' is not definedThe name is not in the local, enclosing, global or built-in namespace, often because it was defined in an inner functionReturn the value, or define it in a scope that encloses the code that uses it
TypeError: 'list' object is not callableA variable named list (or str, id, input) hides the built-inRename the variable. In an interactive session, del list brings the built-in back
SyntaxError: no binding for nonlocal 'x' foundnonlocal was used for a name that only exists globally, or does not existUse 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, type or input.
  • Use nonlocal mainly in closures and decorators that need to keep state. For anything bigger, a class is usually clearer.
  • Prefer import module over from 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

Python Example Code: Find all the pairs of numbers which sum upto `k`

This page shows how to find every pair of numbers in a Python list that adds up to a target value k, a common coding-interview question. The…

Read More

Python Example Code: Program for printing k largest elements in an array

To print the k largest elements of a Python list, you can sort it in descending order and take the first k items. That is what the…

Read More

Python Test Runners – multiprocessing-testrunner

Python tests can run in several processes at once so that a suite of slow, independent tests finishes faster on a multi-core machine. This page explains the…

Read More

Python Test Runners – gevent-testrunner

This page shows how to run Python unittest tests concurrently with gevent greenlets, so that I/O-bound tests overlap instead of running one after another. Below the original…

Read More

AWS Tutorials: Python code to sync S3 Buckets

This page shows how to sync Amazon S3 data with Python and boto3. The script above downloads every object in a bucket to a local folder. The…

Read More

Python Test Runners – Pytest-xdist

pytest-xdist is a pytest plugin that splits a test suite across several worker processes so the tests run in parallel, and the -n option sets how many…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x