Skip to content

Concurrent lazy import reification can call custom hooks multiple times #162480

Open

Description

@tonghuaroot

Bug description:

PEP 810 says exactly one thread performs lazy import reification. When a lazy
binding uses a custom __import__ hook, concurrent readers can all call the
hook before one result replaces the binding. Each reader may receive a
different object.

import builtins
import threading
import types

owner = types.ModuleType("owner")
calls = []
call_lock = threading.Lock()
hook_barrier = threading.Barrier(4)

def import_hook(name, globals=None, locals=None, fromlist=(), level=0):
    with call_lock:
        token = len(calls)
        calls.append(token)
    try:
        hook_barrier.wait(timeout=1)
    except threading.BrokenBarrierError:
        pass
    module = types.ModuleType(name)
    module.token = token
    return module

owner.__dict__["__builtins__"] = dict(
    vars(builtins), __import__=import_hook)
exec("lazy import target", owner.__dict__)

results = [None] * 4
start = threading.Barrier(4)

def access(index):
    start.wait()
    results[index] = owner.target.token

threads = [threading.Thread(target=access, args=(index,)) for index in range(4)]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()

assert calls == [0], calls
assert results == [0] * 4, results

On current main, the hook is called four times and the threads receive
different tokens.

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Linked PRs

Activity

  1. added
    interpreter-core
    type-bug
    on Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-coretopic-lazy-importstype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions