Programming Search⌘K

Featureintro

Modules

Also called module, import, module namespace, sys.modules, importlib.reload, circular import, __name__.

A module is a .py file. The first import runs its code once and makes a module object, and the names that the file defines become the attributes of that object.

Language
Python

Synopsis

# counter.py: the module counter
count = 0

def bump():
    global count
    count += 1

# main.py
import counter        # the first import runs counter.py and binds the name counter
counter.bump()        # modname.itemname
counter.count         # 1
counter.__name__      # 'counter'

Semantics

r1. "A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable name."1 Example: once.

r2. The statements of a module run when it is imported. "These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement."1 Example: once.

r3. Python keeps each loaded module in sys.modules. "This mapping serves as a cache of all modules that have been previously imported".2 "During import, the module name is looked up in sys.modules and if present, the associated value is the module satisfying the import, and the process completes."2 Thus each import of the same name gives the same module object. Example: cache.

r4. "Each module has its own private namespace, which is used as the global namespace by all functions defined in the module."1 Two modules can use the same global name, and the names do not clash. Code outside the module gets a name with "the same notation used to refer to its functions, modname.itemname."1 Example: namespaces.

r5. The module object holds its namespace in a dictionary. "Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]."3 An assignment to m.x changes the namespace of the module, so the functions of the module see the new value. Example: namespaces.

r6. "The built-in function dir() is used to find out which names a module defines. It returns a sorted list of strings".1 Example: namespaces.

r7. A changed source file does not reload itself. "For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter".1 importlib.reload(module) runs the code again: "Python module’s code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module’s dictionary".4 Example: reload.

Examples

The module code runs at the first import only (rules r1 and r2). The second import counter finds the module in sys.modules and does not run the file again.

print("loading counter")
count = 0


def bump():
    global count
    count += 1
    return count
import counter
import counter

print(counter.__name__)
counter.bump()
counter.bump()
print(counter.count)
Output
loading counter
counter
2

All imports of one name give one object, and the object is the value in sys.modules (rule r3). The name after as is only a second name for the same object.

debug = False
import sys

import settings
import settings as config

config.debug = True
print(settings is config)
print(sys.modules["settings"] is settings)
print(settings.debug)
Output
True
True
True

Two modules define the global name, and each function reads the global of its own module (rule r4). An assignment through the module object changes that namespace (rule r5), and dir() lists the names (rule r6).

name = "north"


def who():
    return name
name = "south"


def who():
    return name
import north
import south

name = "main"
print(north.who(), south.who(), name)

south.name = "changed"
print(south.who(), south.__dict__["name"])
print([n for n in dir(north) if not n.startswith("__")])
Output
north south main
changed changed
['name', 'who']

importlib.reload runs the module code again in the same module object (rule r7).

print("running greeting.py")
text = "hello"
import importlib

import greeting

old = greeting
greeting.text = "changed"
importlib.reload(greeting)
print(greeting is old, greeting.text)
Output
running greeting.py
running greeting.py
True hello

Versions

The message of circular differs. CPython 3.12.3 says cannot import name 'foo_var' from partially initialized module 'foo' (most likely due to a circular import). CPython 3.13.14 and 3.14.6 say cannot import name 'foo_var' from 'foo' and add a hint to rename foo.py, which does not apply here. The hint comes from a change in 3.13: "if a script has the same name as a third-party module that it attempts to import and this results in errors, we also display a more helpful error message".5 The other examples give the same output on the three versions.

Pitfalls

Circular imports with from

The FAQ shows two modules that import each other.6 foo starts to run and imports bar. Then bar asks foo for foo_var, but foo has not yet got to the line that sets it. "The last step fails, because Python isn’t done with interpreting foo yet and the global symbol dictionary for foo is still empty."6

from bar import bar_var

foo_var = 1
from foo import foo_var

bar_var = 2

This code raises ImportError, on purpose.

import foo

The FAQ says that "Circular imports are fine where both modules use the “import ” form of import. They fail when the 2nd module wants to grab a name out of the first (“from module import name”) and the import is at the top level."6 In the fixed version, bar keeps a reference to the module and reads the attribute later, when foo is complete.

import bar

foo_var = 1


def total():
    return foo_var + bar.bar_var
import foo

bar_var = 2


def read_foo():
    return foo.foo_var
import bar
import foo

print(foo.total(), bar.read_foo())
Output
3 1

The FAQ also gives two other ways out: put the imports after the definitions that other modules need, or change the design "so that the recursive import is not necessary in the first place."6

An edited module does not change the program

An import of a module that is already in sys.modules does not read the file again (rule r7). In an interactive session, restart the interpreter or call importlib.reload(). A reload does not update other references: "Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects".4 A name bound by from greeting import text keeps the old object.

Comparison

JavaScript modules use import declarations, which "import read-only live bindings which are exported by another module."7 A JavaScript module also has a cycle problem: "With cyclic imports, an imported module may not have finished evaluating, so an imported binding may still be uninitialized."7

Go runs the initialization of each package one time: "If multiple packages import a package, the imported package will be initialized only once. The importing of packages, by construction, guarantees that there can be no cyclic initialization dependencies."8 A Python import cycle is legal and fails only when a name is not ready.

Rust declares modules with mod. For mod garden; the compiler looks for the code "In the file src/garden.rs" or "In the file src/garden/mod.rs".9 In Python, the file itself is the module, and no declaration is necessary.

Implementation notes

CPython stores the compiled bytecode of an imported module: "To speed up loading modules, Python caches the compiled version of each module in the pycache directory under the name module.version.pyc".1 This makes only the load faster: "A program doesn’t run any faster when it is read from a .pyc file than when it is read from a .py file; the only thing that’s faster about .pyc files is the speed with which they are loaded."1

References

  1. The Python Tutorial, 6. Modules, 6. Modules; 6.1. More on Modules; 6.1.3. “Compiled” Python files; 6.3. The dir() Function
  2. The Python Language Reference, 5. The import system, 5. The import system; 5.3.1. The module cache
  3. The Python Language Reference, 3. Data model, 3.2.9. Modules
  4. importlib, The implementation of import, importlib.reload()
  5. What’s New In Python 3.13, Improved error messages
  6. Programming FAQ, What are the “best practices” for using import in a module?; How can I have modules that mutually import each other?
  7. import, JavaScript reference, MDN, Description
  8. The Go Programming Language Specification, Package initialization
  9. The Rust Programming Language, 7.2. Defining Modules to Control Scope and Privacy, Modules Cheat Sheet

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source