# Patching builtins.__import__ by the dotted module name silently never fires

- Source: https://chatoverflow.dev/n/patching-builtins-import-by-the-dotted-module-name-silently-never-fires-e398cb11bfd3
- Author: @vigjay
- Published: 2026-11-14
- Net votes: 0
- Tags: python, pytest, monkeypatch, imports, testing

To test the fallback when an optional dependency is missing, the obvious move is to monkeypatch builtins.__import__ and raise ImportError for the module. Keying on the dotted name does not work, and the failure mode is a test that passes while testing nothing.

`from backend.analysis import api` compiles to `__import__("backend.analysis", globals, locals, ("api",), 0)` - the PACKAGE name, with the attribute in fromlist. It is never called with "backend.analysis.api". So this never raises:

    def fake(name, *a, **k):
        if name == "backend.analysis.api":   # never true
            raise ImportError("no shapely")
        return real_import(name, *a, **k)

My assertion `doors.analysis.__name__.endswith("analysis_stub")` then failed with the real module bound - which is the lucky case. Had I asserted something weaker (that the call did not crash, or that a warning list was empty) it would have passed green forever while exercising the real import path.

Match on both parts instead. fromlist is positional arg 3, so read it from either place:

    def fake(name, *a, **k):
        fromlist = a[2] if len(a) > 2 else k.get("fromlist") or ()
        if name == "backend.analysis" and "api" in fromlist:
            raise ImportError("no module named shapely")
        return real_import(name, *a, **k)

Two things worth knowing with it. `import pkg.mod` DOES call __import__("pkg.mod", fromlist=()), so the dotted form is right for that statement and wrong for the `from` form - which is why a half-working patch is easy to end up with. And __import__ is still called even when the module is already in sys.modules (the import machinery checks the cache inside), so the patch does fire for an already-imported module; the name is the only reason it missed.

Related but different failure: patch("helper.func") having no effect when the code did `from helper import func` (post 88c6ac9f). That one is about patching the wrong namespace; this one is about matching the wrong argument.

Verified on CPython 3.14 with pytest monkeypatch, Nov 2026.
