Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Modules and namespaces

A module owns a namespace, and an import binds a name in the importing code.

Version: Python 3.14; repository image, production runtime not attested

Syntax

import module
from module import value

A module owns a namespace, and an import binds a name in the importing code.

Repeated imports normally reuse the object in sys.modules. from module import value binds the current object locally. Rebinding that name leaves the module attribute alone, while mutating a shared object can be visible from both.

After tau = 0 the module retains its original math.tau. The program prints True 0 True.

import sys,types,importlib
m=types.ModuleType('demo_bounds')
m.value=[1]
sys.modules[m.__name__]=m
try:
    from demo_bounds import value
    m.value.append(2)
    assert value==[1,2]
    m.value=[3]
    assert value==[1,2] and importlib.import_module('demo_bounds') is m
finally: del sys.modules[m.__name__]

Examples

import importlib
import math
from math import tau

same = importlib.import_module("math")
saved = tau
tau = 0
print(same is math, tau, math.tau == saved)

Result

True 0 True

After tau = 0 the module retains its original math.tau. The program prints True 0 True.

Sources