Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Python Namespaces & Variable Scope: Understanding Names, Bindings, and Scopes

Python Namespaces & Variable Scope

Explore how names, namespaces, and variable scopes work in Python, with clear examples and best practices.

What Is a Name in Python?

In “The Zen of Python” (import this), the last line reads, “Namespaces are one honking great idea -- let's do more of those!” So what are these namespaces? First, let’s define a name.

A name, or identifier, is a label that references an object. Everything in Python is an object, and a name provides a convenient way to access it.

For example, when we execute a = 2, the integer 2 is stored in memory and a becomes its reference. The built‑in id() function returns the memory address of an object.

# Note: Your id values may differ

a = 2
print('id(2) =', id(2))
print('id(a) =', id(a))

Output

id(2) = 9302208
id(a) = 9302208

Both names point to the same object, so their id() values match. Let’s see what happens when we rebind a:

# Note: Your id values may differ

a = 2
print('id(a) =', id(a))
a = a + 1
print('id(a) =', id(a))
print('id(3) =', id(3))
b = 2
print('id(b) =', id(b))
print('id(2) =', id(2))

Output

id(a) = 9302208
id(a) = 9302240
id(3) = 9302240
id(b) = 9302208
id(2) = 9302208

When a = a + 1 is executed, a new object 3 is created, and a now references it. Notice that id(a) and id(3) are identical. The subsequent assignment b = 2 simply binds b to the existing 2 object, avoiding duplicate storage.

Python Namespaces & Variable Scope: Understanding Names, Bindings, and Scopes

This dynamic name binding is what makes Python flexible: a single identifier can point to values of any type—including functions.

def printHello():
    print("Hello")


a = printHello

a()

Output

Hello

The identifier a now references the function printHello, which we can invoke directly.


What Is a Namespace?

A namespace is a mapping from names to objects. Think of it as a dictionary that holds every identifier you have defined along with its associated object.

Python supports multiple namespaces simultaneously, each isolated from the others. The interpreter creates a global namespace containing all built‑in names that persists for the life of the session. Every module gets its own global namespace, and each function or class definition introduces a new local namespace.

Python Namespaces & Variable Scope: Understanding Names, Bindings, and Scopes

Variable Scope in Python

While namespaces exist, the scope determines where a name can be accessed without qualification.

At any moment, a program has at least three nested scopes:

  1. The local scope of the currently executing function.
  2. The global scope of the module.
  3. The built‑in scope that is always available.

When a name is referenced inside a function, Python searches the local namespace first, then the global, and finally the built‑in namespace. If a function contains another function, the inner one introduces a new, nested scope.


Example: Scope and Namespace Interaction

Consider the following code:

def outer_function():
    b = 20
    def inner_func():
        c = 30


a = 10

Here, a lives in the module’s global namespace. The variable b is local to outer_function, and c belongs to the nested local namespace of inner_func.

Inside inner_func, c is local, b is non‑local, and a is global. You can read and write c, but only read b and a unless you declare them explicitly with global or nonlocal.

Here’s a more concrete illustration:

def outer_function():
    a = 20
    def inner_function():
        a = 30
        print('a =', a)
    inner_function()
    print('a =', a)


a = 10
outer_function()
print('a =', a)

The output demonstrates three distinct a bindings:

a = 30
a = 20
a = 10

To force all assignments to the global a, use the global keyword:

def outer_function():
    global a
    a = 20
    def inner_function():
        global a
        a = 30
        print('a =', a)
    inner_function()
    print('a =', a)


a = 10
outer_function()
print('a =', a)

The output now reflects a single, global a:

a = 30
a = 30
a = 30

These examples illustrate how Python’s namespace and scope rules govern variable visibility and mutation.


Python

  1. Python Keywords and Identifiers: Mastering Reserved Words and Naming Conventions
  2. Python Statements, Indentation, and Comments: A Clear Guide
  3. Python Variables, Constants, and Literals – A Comprehensive Guide
  4. Mastering Python Type Conversion & Casting: A Comprehensive Guide
  5. Mastering Python I/O and Module Imports: A Practical Guide
  6. Mastering Python Loop Control: break & continue
  7. Understanding Python Global, Local, and Nonlocal Variables
  8. Mastering Directory and File Operations in Python
  9. Python vs JavaScript: Key Differences, Features, and When to Choose Each
  10. Python vs Ruby: A Comprehensive Comparison of Features, Advantages, and Use Cases