← Writing

Importing Is Executing

23 min readSystemsPythonCpythonCImportLinux
Contents

Python 3.8 makes 479 system calls to run a program that does nothing, and imports 34 modules before the program’s first line. import json adds about 270 more calls. Put 100 directories on PYTHONPATH and the same import json makes 4,372, and on Python 2.7 18,469, of which 17,705 fail, because Python 2 asks the file system for every name it might be looking for in every directory it might be in. And the bytecode it finds at the end of that search is trusted on the strength of two numbers, the source file’s modification time and its size: change a file without changing either and Python keeps running the old code.

import looks like a declaration, and it is a program. This post follows it through the Python 3.8 on Ubuntu 20.04: what runs before your first line, how a name becomes a file, how the bytecode cache is validated, what runs as a side effect, how a C extension gets into the process and why it never leaves, and what happens when two modules import each other.

This is Part 15 of a series on the CPython runtime. Part 2 started from a code object, and this is where code objects come from. Part 10 wrote a C extension, and this is how one is loaded. It is written for Python programmers who have written a little C. Everything here ran on a stock Ubuntu 20.04 from its release archive, with its Python 3.8.2, its Python 2.7 (2.7.18 release candidate 1) and strace 4.26. The note at the end says exactly where and how.

Before the first line

import sys
names = sorted(sys.modules)              # before this file imports anything
import textwrap
print(len(names), "modules loaded before the first line of this file:")
print(textwrap.fill(" ".join(names), 100))
for name in ("_frozen_importlib", "_frozen_importlib_external", "zipimport"):
    print("%-27s origin: %s" % (name, sys.modules[name].__spec__.origin))
$ python3 startup.py
34 modules loaded before the first line of this file:
__main__ _abc _codecs _collections_abc _frozen_importlib _frozen_importlib_external _imp _io _signal
_sitebuiltins _stat _thread _warnings _weakref abc builtins codecs encodings encodings.aliases
encodings.latin_1 encodings.utf_8 genericpath io marshal os os.path posix posixpath site
sitecustomize stat sys time zipimport
_frozen_importlib           origin: frozen
_frozen_importlib_external  origin: frozen
zipimport                   origin: frozen

Thirty-four modules, counting __main__, of three kinds. Some are built in, compiled into the python3 binary with their init functions in a table: sys, builtins, posix, _io, _thread, marshal. Some are frozen: Python modules whose bytecode is compiled into the binary as C arrays of bytes. The three frozen ones here are the import system itself, importlib._bootstrap and importlib._bootstrap_external, which are Python code that runs before any Python file can be read, and so can’t be read from a file. zipimport joined them in 3.8, when it was rewritten from C into Python. The rest are ordinary .py files read from /usr/lib/python3.8, all pulled in by site, the module that sets up sys.path: the codecs for the terminal’s encoding, os, stat, and Debian’s own sitecustomize.

-X importtime, new in 3.7, times every import as it happens. A short script sums it up:

# toptime.py: summarise python -X importtime output: count, total, and the slowest imports by cumulative time
import sys
rows = []
for line in open(sys.argv[1]):
    if line.startswith("import time:") and "|" in line and "self [us]" not in line:
        self_us, cum_us, name = [x.strip() for x in line[len("import time:"):].split("|")]
        rows.append((int(self_us), int(cum_us), name))
print("%d modules imported, %.1f ms in their own code" % (len(rows), sum(r[0] for r in rows) / 1000))
for self_us, cum_us, name in sorted(rows, key=lambda r: -r[0])[:8]:
    print("  self %6.1f ms   cumulative %6.1f ms   %s" % (self_us / 1000, cum_us / 1000, name))
$ python3 -X importtime -c pass 2> it_pass.txt; python3 toptime.py it_pass.txt
24 modules imported, 2.8 ms in their own code
  self    0.5 ms   cumulative    0.5 ms   _collections_abc
  self    0.2 ms   cumulative    0.6 ms   encodings
  self    0.2 ms   cumulative    1.0 ms   os
  self    0.2 ms   cumulative    0.2 ms   _frozen_importlib_external
  self    0.2 ms   cumulative    0.2 ms   codecs
  self    0.2 ms   cumulative    1.3 ms   site
  self    0.2 ms   cumulative    0.2 ms   encodings.aliases
  self    0.1 ms   cumulative    0.2 ms   stat
$ python3 -X importtime -c "import numpy" 2> it_numpy.txt; python3 toptime.py it_numpy.txt
281 modules imported, 60.4 ms in their own code
  self    1.4 ms   cumulative    1.4 ms   numpy.core.defchararray
  self    1.4 ms   cumulative    9.0 ms   numpy.core.multiarray
  self    1.3 ms   cumulative    1.3 ms   numpy.ma.core
  self    1.2 ms   cumulative    1.3 ms   numpy.core.fromnumeric
  self    1.1 ms   cumulative    1.8 ms   ssl
  self    1.1 ms   cumulative    1.3 ms   numpy.lib.function_base
  self    1.0 ms   cumulative    3.5 ms   numpy.core.numeric
  self    0.9 ms   cumulative    0.9 ms   platform

Twenty-four imports that importtime can see (the built-in and frozen ones before it starts aren’t counted), 2.8 ms of module code, for a program that does nothing. import numpy runs 281 modules, ssl and logging among them, and 60 ms of their top-level code. A module’s top level is a function that runs once, at import, and everything at that level runs: class definitions are executed, functions are created, constants computed, and other modules imported. For the whole process, measured from outside:

# wall.py: run each command ten times and report the best wall time
import subprocess, sys, time
for cmd in sys.argv[1:]:
    best = float("inf")
    for _ in range(10):
        t = time.perf_counter()
        subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        best = min(best, time.perf_counter() - t)
    print("%7.1f ms  %s" % (best * 1000, cmd))
$ python3 wall.py "python3 -c pass" "python3 -S -c pass" "python3 -I -c pass" "python3 -c 'import numpy'" "python2.7 -c pass"
    6.0 ms  python3 -c pass
    4.4 ms  python3 -S -c pass
    5.6 ms  python3 -I -c pass
   59.5 ms  python3 -c 'import numpy'
    4.5 ms  python2.7 -c pass

-S skips site, which saves a quarter of the start-up and leaves no sys.path entries for installed packages. -I, isolated mode, ignores the environment and the user’s own site directory but still runs site.

From a name to a file

import json asks each finder on sys.meta_path in turn: the built-in finder, the frozen finder, and PathFinder, which walks sys.path. For each directory on it, PathFinder asks that directory’s FileFinder, which knows four kinds of file a module can be: an extension module (.cpython-38-x86_64-linux-gnu.so, .abi3.so, .so), a source file (.py), or bytecode with no source (.pyc), or a directory, which is a package. strace, which logs every system call a process makes, shows what that costs. A short script summarises its log:

# sysc.py: summarise an strace -f log: calls per system call, and how many failed with ENOENT
import collections, re, sys
calls, missing = collections.Counter(), collections.Counter()
for line in open(sys.argv[1]):
    m = re.match(r"\d+\s+(\w+)\(", line)
    if not m:
        continue
    calls[m[1]] += 1
    if "ENOENT" in line:
        missing[m[1]] += 1
print("%d system calls, %d of them failed with ENOENT" % (sum(calls.values()), sum(missing.values())))
for name, n in calls.most_common(6):
    print("  %-10s %6d  (%d ENOENT)" % (name, n, missing[name]))
$ strace -f -o t_pass.txt python3 -c pass; python3 sysc.py t_pass.txt
479 system calls, 23 of them failed with ENOENT
  stat           86  (17 ENOENT)
  rt_sigaction     68  (0 ENOENT)
  fstat          51  (0 ENOENT)
  mmap           44  (0 ENOENT)
  openat         37  (5 ENOENT)
  read           37  (0 ENOENT)
$ strace -f -o t_json.txt python3 -c "import json"; python3 sysc.py t_json.txt
753 system calls, 29 of them failed with ENOENT
  stat          165  (23 ENOENT)
  fstat          88  (0 ENOENT)
  read           72  (0 ENOENT)
  rt_sigaction     68  (0 ENOENT)
  lseek          67  (0 ENOENT)
  openat         57  (5 ENOENT)
$ strace -f -o t_py2.txt python2.7 -c "import json"; python3 sysc.py t_py2.txt
866 system calls, 305 of them failed with ENOENT
  openat        305  (230 ENOENT)
  fstat         110  (0 ENOENT)
  read          109  (0 ENOENT)
  stat          100  (74 ENOENT)
  close          75  (0 ENOENT)
  rt_sigaction     68  (0 ENOENT)

The same import, on the same machine, from two Pythons. Python 3 failed 29 calls in all, start-up included. Python 2 failed 305. To see why, give both of them a long sys.path, one hundred empty directories ahead of the standard ones, the way a large deployment with many installed packages or a long PYTHONPATH would:

$ mkdir -p /tmp/many; for i in $(seq 1 100); do mkdir -p /tmp/many/d$i; done
$ P=$(python3 -c 'print(":".join("/tmp/many/d%d" % i for i in range(1, 101)))')
$ PYTHONPATH=$P strace -f -o t_py2_100.txt python2.7 -c "import json"; python3 sysc.py t_py2_100.txt
18469 system calls, 17705 of them failed with ENOENT
  openat      14805  (14730 ENOENT)
  stat         3200  (2974 ENOENT)
  fstat         110  (0 ENOENT)
  read          109  (0 ENOENT)
  close          75  (0 ENOENT)
  rt_sigaction     68  (0 ENOENT)
$ PYTHONPATH=$P strace -f -o t_json100.txt python3 -c "import json"; python3 sysc.py t_json100.txt
4372 system calls, 29 of them failed with ENOENT
  stat         3265  (23 ENOENT)
  getdents64    218  (0 ENOENT)
  fstat         188  (0 ENOENT)
  openat        157  (5 ENOENT)
  close         155  (0 ENOENT)
  read           72  (0 ENOENT)

Python 2 made 17,705 calls that failed. Here is what it did in one of the empty directories:

$ grep -E "d17\b|d17/" t_py2_100.txt | head -12
1738  stat("/tmp/many/d17", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0
1738  stat("/tmp/many/d17", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0
1738  stat("/tmp/many/d17/site", 0x7ffc9975b3e0) = -1 ENOENT (No such file or directory)
1738  openat(AT_FDCWD, "/tmp/many/d17/site.x86_64-linux-gnu.so", O_RDONLY) = -1 ENOENT (No such file or directory)
1738  openat(AT_FDCWD, "/tmp/many/d17/site.so", O_RDONLY) = -1 ENOENT (No such file or directory)
1738  openat(AT_FDCWD, "/tmp/many/d17/sitemodule.so", O_RDONLY) = -1 ENOENT (No such file or directory)
1738  openat(AT_FDCWD, "/tmp/many/d17/site.py", O_RDONLY) = -1 ENOENT (No such file or directory)
1738  openat(AT_FDCWD, "/tmp/many/d17/site.pyc", O_RDONLY) = -1 ENOENT (No such file or directory)
1738  stat("/tmp/many/d17/os", 0x7ffc9975af30) = -1 ENOENT (No such file or directory)
1738  openat(AT_FDCWD, "/tmp/many/d17/os.x86_64-linux-gnu.so", O_RDONLY) = -1 ENOENT (No such file or directory)
1738  openat(AT_FDCWD, "/tmp/many/d17/os.so", O_RDONLY) = -1 ENOENT (No such file or directory)
1738  openat(AT_FDCWD, "/tmp/many/d17/osmodule.so", O_RDONLY) = -1 ENOENT (No such file or directory)

Python 2’s import, in C in Python/import.c, tries every possible file name in every directory: is there a package directory called site, then site.x86_64-linux-gnu.so, site.so, sitemodule.so, site.py, site.pyc, each one a system call that fails. Then the same for os, and every other module, in every one of the hundred directories. That’s the stat storm: the cost of an import grows as modules times directories times suffixes, and on a network file system each failed call is a round trip to a server, unless the client caches the failure.

Python 3 does it differently:

$ grep -E "d17\b|d17/" t_json100.txt | head -8
1844  stat("/tmp/many/d17", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0
1844  stat("/tmp/many/d17", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0
1844  stat("/tmp/many/d17", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0
1844  openat(AT_FDCWD, "/tmp/many/d17", O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_DIRECTORY) = 4
1844  stat("/tmp/many/d17", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0
1844  stat("/tmp/many/d17", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0
1844  stat("/tmp/many/d17", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0
1844  stat("/tmp/many/d17", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0

It opens the directory once, lists it with getdents64, and keeps the listing in the FileFinder as a set of names, so finding out that site.py isn’t in d17 is a lookup in a Python set, not a system call. What it still does, every time it searches that directory, is stat it, to see whether the directory’s modification time has changed since the listing (FileFinder.find_spec in importlib/_bootstrap_external.py). One stat per directory per top-level import, and no failures: 29 failed calls with or without the hundred directories.

Fewer system calls didn’t mean faster here:

$ PYTHONPATH=$P python3 wall.py "python3 -c 'import numpy'" "python3 -c 'import json'" "python2.7 -c 'import json'"
   82.7 ms  python3 -c 'import numpy'
   16.8 ms  python3 -c 'import json'
   13.5 ms  python2.7 -c 'import json'
$ python3 wall.py "python3 -c 'import json'" "python2.7 -c 'import json'"
    9.5 ms  python3 -c 'import json'
    5.4 ms  python2.7 -c 'import json'

The hundred directories added 8 ms to Python 2’s import json and 7 ms to Python 3’s. Python 3 made a quarter of the extra system calls and paid nearly the same, because its search runs in Python: for every module and every directory, PathFinder and FileFinder.find_spec run as bytecode, through the eval loop, where Python 2 ran a C loop. This chroot’s file system is a fast local one, where a failed openat costs well under a microsecond. On NFS, where each one is a network round trip, the system calls would dominate and Python 3’s design would win by far. import numpy grew by 23 ms, for 102 searches of sys.path: a package’s submodules, which are most of its 281, are searched for only in the package’s own directory, its __path__.

One hundred directories on the path

The same three imports with the standard sys.path and with 100 empty directories ahead of it.

standard sys.path+100 directories

Python 2 tries every file name in every directory, and almost all of its extra calls fail. Python 3 lists each directory once and then only checks its modification time, but runs its search as Python code, so on this fast local disk the hundred directories cost both about the same time.

The bytecode cache, and what it trusts

A .py file found is compiled to a code object, and the code object is written to __pycache__/<name>.cpython-38.pyc with marshal, so the next run can skip the compiler. The .pyc starts with a 16-byte header:

$ mkdir pyc2; printf 'X = 1\n' > pyc2/mod.py; touch -d '2020-06-01 12:00:00 UTC' pyc2/mod.py; (cd pyc2 && python3 -c "import mod")
$ od -A d -t x1 pyc2/__pycache__/mod.cpython-38.pyc | head -2
0000000 55 0d 0d 0a 00 00 00 00 c0 ed d4 5e 06 00 00 00
0000016 e3 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
# pychead.py: decode the 16-byte header of a .pyc file
import importlib.util, struct, sys, time
data = open(sys.argv[1], "rb").read(16)
magic, flags, a, b = struct.unpack("<4sIII", data)
print("magic:", magic.hex(), "= %d, this interpreter's is %d" % (
    int.from_bytes(magic[:2], "little"), int.from_bytes(importlib.util.MAGIC_NUMBER[:2], "little")))
if flags == 0:
    print("flags: 0, timestamp-based")
    print("source mtime: %d (%s UTC)" % (a, time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(a))))
    print("source size: %d bytes" % b)
else:
    print("flags: %d, hash-based, %s" % (flags, "checked" if flags & 2 else "unchecked"))
    print("source hash:", data[8:].hex())
$ python3 pychead.py pyc2/__pycache__/mod.cpython-38.pyc
magic: 550d0d0a = 3413, this interpreter's is 3413
flags: 0, timestamp-based
source mtime: 1591012800 (2020-06-01 12:00:00 UTC)
source size: 6 bytes

Four fields. The magic number, 3413 for every 3.8 release, changes whenever the bytecode format does, so a 3.7 interpreter won’t load 3.8’s bytecode, and the \r\n in its last two bytes catches a file mangled by a text-mode transfer. The flags word was added by PEP 552 in 3.7. Then the source file’s modification time, in whole seconds, and its size in bytes. The marshalled code object starts at byte 16, with e3, marshal’s code for a code object.

When a later import finds both mod.py and this .pyc, it compares the source’s current mtime and size with the two in the header, and if both match it loads the bytecode without looking at the source again. Nothing else is checked. So:

import os, subprocess, sys
os.makedirs("pyc", exist_ok=True)

def edit(text):
    with open("pyc/mod.py", "w") as f:
        f.write(text)
    os.utime("pyc/mod.py", (1590000000, 1590000000))     # the same mtime every time

def run():
    r = subprocess.run([sys.executable, "-c", "import mod; print(mod.X)"], cwd="pyc", capture_output=True, text=True)
    return r.stdout.strip()

edit("X = 1\n");  print("source says X = 1, import gives", run())
edit("X = 2\n");  print("source says X = 2, import gives", run())
subprocess.run([sys.executable, "-m", "compileall", "-q", "-f", "--invalidation-mode", "checked-hash", "pyc"])
print("recompiled with checked-hash, import gives", run())
edit("X = 3\n");  print("source says X = 3, import gives", run())
$ python3 stale.py
source says X = 1, import gives 1
source says X = 2, import gives 1
recompiled with checked-hash, import gives 2
source says X = 3, import gives 3

The second edit changed the code and kept the size and the timestamp, and Python ran the old code. Here the script reset the mtime on purpose. In practice the same thing happens when a file is edited twice within one second, when a build tool or git checkout or a copy that preserves timestamps writes an older time, or when a container image is built with every timestamp set to the same value, so that a reproducible build is reproducibly stale.

PEP 552’s answer is the hash-based .pyc: instead of a time and a size, the header holds a 64-bit SipHash of the source file’s bytes.

$ python3 pychead.py pyc/__pycache__/mod.cpython-38.pyc
magic: 550d0d0a = 3413, this interpreter's is 3413
flags: 3, hash-based, checked
source hash: da468806739a8d67

A checked hash pyc (flags 3: hash-based, and check the source) makes the import read and hash the source every time, so the edit to X = 3 was seen. An unchecked one (flags 1) is never compared at all, which is for systems that guarantee the pyc is rebuilt whenever the source changes. Both make the .pyc depend only on the source, not on when it was written, which is what reproducible packaging needed: py_compile writes checked hash pycs by default whenever SOURCE_DATE_EPOCH is set in the environment, the variable that reproducible-build tools set.

What a .pyc says about its source

The first 16 bytes of two .pyc files written by Python 3.8.2; the code object starts at byte 16.

Hover or focus a field.

Numbers are stored little-endian. On import, a timestamp-based pyc is used if the source's current mtime and size equal the two stored here; a checked-hash pyc is used if the source's hash equals the one stored.

Code that runs because a file exists

site reads every .pth file in each site-packages directory. A line in one is either a path to add to sys.path, or, if it starts with import, a line of Python that site passes to exec. These are the directories:

$ python3 -c 'import site; print(site.getsitepackages())'
['/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages', '/usr/lib/python3.8/dist-packages']

So a file dropped into one of them runs in every Python process on the machine, at start-up, before -c or the script or anything else, whether or not anything imports the package it came with:

$ cat /usr/local/lib/python3.8/dist-packages/zz_demo.pth
import sys; sys.stderr.write("a .pth file ran this\n")
$ python3 -c pass
a .pth file ran this
$ python3 -S -c pass

This is how setuptools makes pip install -e work, by listing the project’s directory in a .pth file, and it’s also a way for any installed package to run code in every interpreter, which is worth knowing when deciding what to install as root. This minimal system has no .pth files at all, and the only way to turn them off is -S, which also turns off every installed package.

sys.path[0] is a related trap. It’s the directory of the script being run (or the current directory, for -c), and it comes first, ahead of the standard library. Here’s a directory with a file called random.py, which prints a line, and an app.py which only imports tempfile:

print("this is shadow/random.py, not the standard library's")
import tempfile
print(tempfile.mkdtemp())
$ cd shadow && python3 app.py
this is shadow/random.py, not the standard library's
Traceback (most recent call last):
  File "app.py", line 1, in <module>
    import tempfile
  File "/usr/lib/python3.8/tempfile.py", line 184, in <module>
    from random import Random as _Random
ImportError: cannot import name 'Random' from 'random' (/work/p15/shadow/random.py)

app.py never imported random. tempfile did, from inside the standard library, and got the neighbour of the script, because module names are global to the process. Earlier in this series, in Part 11, a script of mine called pickle5.py did the same to NumPy, which tries to import a package of that name.

A module that is half there

Before running a module’s code, the import system creates the module object and puts it in sys.modules, then runs the code in its namespace. A second import of the same name, from anywhere, finds that entry and returns it without waiting. That’s what makes circular imports possible, and it’s also what makes them fail. With circ/a.py:

import b
X = 1

and circ/b.py:

import sys
a = sys.modules["a"]
print("b sees a:", a, "with X?", hasattr(a, "X"), flush=True)
from a import X
$ cd circ && python3 -c "import a"
b sees a: <module 'a' from '/work/p15/circ/a.py'> with X? False
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/work/p15/circ/a.py", line 1, in <module>
    import b
  File "/work/p15/circ/b.py", line 4, in <module>
    from a import X
ImportError: cannot import name 'X' from partially initialized module 'a' (most likely due to a circular import) (/work/p15/circ/a.py)

a is in sys.modules while its first line is still running, as an object with no X yet, because X = 1 is on the second line and hasn’t run. from a import X looks up an attribute that isn’t there yet. The words “partially initialized module” and the hint “(most likely due to a circular import)” are new in Python 3.8, in the IMPORT_FROM code in ceval.c. Before 3.8 the message was only “cannot import name ‘X’”, and the cause had to be worked out. import a followed by a.X inside a function would have worked, because by the time the function runs, a has finished.

C extensions: in, and never out

An extension module is a shared library. Finding _decimal ends in ExtensionFileLoader, which calls _imp.create_dynamic, which on Linux calls dlopen and then looks up a symbol named PyInit_ plus the module’s name:

$ LD_DEBUG=files python3 -c "import _decimal" 2>&1 | grep -E "file=.*(decimal|mpdec)" | sed 's/^ *[0-9]*:[[:space:]]*//'
file=/usr/lib/python3.8/lib-dynload/_decimal.cpython-38-x86_64-linux-gnu.so [0];  dynamically loaded by python3 [0]
file=/usr/lib/python3.8/lib-dynload/_decimal.cpython-38-x86_64-linux-gnu.so [0];  generating link map
file=libmpdec.so.2 [0];  needed by /usr/lib/python3.8/lib-dynload/_decimal.cpython-38-x86_64-linux-gnu.so [0]
file=libmpdec.so.2 [0];  generating link map
opening file=/usr/lib/python3.8/lib-dynload/_decimal.cpython-38-x86_64-linux-gnu.so [0]; direct_opencount=1
$ nm -D --defined-only /usr/lib/python3.8/lib-dynload/_decimal.cpython-38-x86_64-linux-gnu.so | grep PyInit
00000000000188e0 T PyInit__decimal

The dynamic linker loads _decimal’s library and the C library it depends on, libmpdec, maps them into the process, runs their initialisers, and CPython calls PyInit__decimal, the function Part 10 wrote by hand for its own module. From then on it’s C code in the process’s address space, and Python can’t take it back out:

import gc, sys

def mapped():
    return sum(1 for line in open("/proc/self/maps") if "_decimal" in line)

print("mappings of _decimal before import:", mapped())
import _decimal
first_type = _decimal.Decimal
print("after import:", mapped(), "from", _decimal.__file__)
del sys.modules["_decimal"], _decimal
gc.collect()
print("after removing every reference:", mapped())
import _decimal
print("imported again; same Decimal type as before?", _decimal.Decimal is first_type)
$ python3 unload.py
mappings of _decimal before import: 0
after import: 6 from /usr/lib/python3.8/lib-dynload/_decimal.cpython-38-x86_64-linux-gnu.so
after removing every reference: 6
imported again; same Decimal type as before? True

There’s no dlclose anywhere in CPython’s loader for Linux (Python/dynload_shlib.c), so the library stays mapped for the life of the process. And importing it again doesn’t run PyInit__decimal again. For a module that uses the classic single-phase initialisation, as _decimal does in 3.8, the import system kept a copy of the module’s dictionary the first time (m_copy in Python/import.c) and makes the new module from that copy, so the types in it are the same objects as before. importlib.reload on an extension module doesn’t reload anything. PEP 489’s multi-phase initialisation, available since 3.5, lets an extension create a fresh module each time, but its C state, its static variables, is still one copy per process, which is why a C extension and an interpreter that wants to start over don’t mix.

What we covered

  • Python 3.8 runs 34 modules before a program’s first line, three of them frozen into the binary, including the import system itself, and 479 system calls for python3 -c pass.
  • Python 2.7 found modules by trying every file name in every directory: 18,469 system calls for import json with 100 extra path entries, 17,705 of them failures. Python 3 lists each directory once and checks its mtime per search, 4,372 calls with no extra failures, though its search, being Python, wasn’t faster on a local disk.
  • A .pyc is validated by the source’s mtime and size. Change a file without changing either and the old bytecode runs. PEP 552’s checked hash pycs compare the source’s hash instead.
  • A .pth file with an import line runs code in every interpreter on the machine. A file next to the script shadows the standard library for every module in the process.
  • A module is in sys.modules before its code has finished, which makes circular imports possible and from imports from them fail, with a clearer message in 3.8.
  • An extension module is dlopened, entered through PyInit_<name>, and never unloaded. Importing it again reuses the first module’s dictionary.

The next post looks at what happens when the process splits, by fork, by threads, or by a second interpreter inside the same process, and at what each of them shares that it shouldn’t.

A note on the evidence

What I ran, and where. Everything ran in a chroot of Ubuntu 20.04 (focal), built with debootstrap from the release archive, with that archive’s packages only: python3.8 3.8.2-1ubuntu1, python2.7 2.7.18~rc1-2, python3-numpy 1:1.17.4-5ubuntu3, libmpdec2 2.4.2-3, strace 4.26-0.2ubuntu3 and binutils 2.34-6ubuntu1. The chroot ran on a newer host kernel. The system calls a program makes are chosen by its own code and the C library in the chroot (glibc 2.31), so the counts are focal’s, but the times would differ on focal’s own kernel and on other file systems: /tmp here is a local disk. Each script was extracted from this page and run as shown, with outputs captured to files and pasted from them. The .pth file was created and removed around the commands shown.

The numbers. System call counts are from one strace run each, and varied by a few calls between runs (753 and 755 for import json). Wall times are the best of ten runs from wall.py, from three invocations in one session, and moved by about 0.5 ms between invocations. The start-up module count includes Debian’s sitecustomize. A complete rerun of every command on this page, extracted from the page into a fresh directory, gave the same outputs apart from times, process ids and paths: system call counts within 8 calls, the same failures, the same headers, errors and mappings. One -X importtime run of import numpy is a single sample, and in the rerun it took 124 ms where the one above took 60, while the best of ten wall times moved only from 59.5 to 63.5 ms, so treat that table’s milliseconds as one run’s.

What I read rather than ran. The directory mtime check is FileFinder.find_spec in Lib/importlib/_bootstrap_external.py, and the pyc validation _validate_timestamp_pyc in the same file, both at v3.8.2. That the circular-import message is new in 3.8 is from comparing Python/ceval.c at v3.7.5 and v3.8.2. The absence of dlclose is from Python/dynload_shlib.c and m_copy from Python/import.c at v3.8.2. py_compile choosing checked hashes under SOURCE_DATE_EPOCH is from Lib/py_compile.py at v3.8.2. What Python 2’s import tries is from the strace log, not from reading Python 2’s source. The importlib history is from the 3.1 and 3.3 “What’s New” documents. That pip install -e works through a .pth file is from setuptools’ develop command, which I didn’t run here.

Not covered. Python 3.9 is in beta and its import system changes little that this post measured. Zip imports, namespace packages (PEP 420) and import hooks get a sentence or nothing.

More