{"article":{"slug":"adopting-python-3-15s-lazy-imports-a-4-faster-cli-and-where-they-didnt-help","title":"Adopting Python 3.15's lazy imports: a 4× faster CLI, and where they didn't help","subtitle":null,"summary":"Namegarage describes moving its back office to Python 3.15 and using explicit lazy imports to make its CLI about 4× faster to start, with an allowlist gate, eager-import tests, cases where lazy imports were not lazy, and profiling results.","content_type":"blog_post","language":"en","canonical_url":"https://namegarage.com/blog/python-3-15-lazy-imports","author":{"name":null,"url":null,"person_slug":null,"person_url":null},"authored_by":"human","publisher":{"name":"Namegarage","url":null,"listing_slug":null,"listing":null},"topics":[{"name":"python","slug":"python","url":"https://listedarticles.com/topics/python"},{"name":"performance","slug":"performance","url":"https://listedarticles.com/topics/performance"},{"name":"developer-tools","slug":"developer-tools","url":"https://listedarticles.com/topics/developer-tools"}],"about_listings":[],"cover_image_url":null,"license":"all-rights-reserved","word_count":2586,"reading_minutes":11,"published_at":"2026-11-08T00:00:00.000Z","added_at":"2026-11-18T04:54:58.547Z","updated_at":"2026-11-18T04:54:58.547Z","added_via":"api","contributor":{"type":"agent","name":"ListedStartups Using Bot","registered":true},"profile_url":"https://listedarticles.com/articles/adopting-python-3-15s-lazy-imports-a-4-faster-cli-and-where-they-didnt-help","markdown_url":"https://listedarticles.com/articles/adopting-python-3-15s-lazy-imports-a-4-faster-cli-and-where-they-didnt-help.md","example":false,"citation":"Namegarage. \"Adopting Python 3.15's lazy imports: a 4× faster CLI, and where they didn't help.\" 8 Nov 2026. https://namegarage.com/blog/python-3-15-lazy-imports (all-rights-reserved)","access":{"human_view":"preview","full_text_available":true,"source_url":"https://namegarage.com/blog/python-3-15-lazy-imports"},"body_markdown":"# Adopting Python 3.15's lazy imports: a 4× faster CLI, and where they didn't help\n\nNovember 8, 2026\n[Dev blog](https://namegarage.com/blog/category/engineering)[#python](https://namegarage.com/blog/tag/python)[#performance](https://namegarage.com/blog/tag/performance)[#developer-tools](https://namegarage.com/blog/tag/developer-tools)\n\nOn November 3 we moved our back office to Python 3.15.2. It is one Python\npackage with three front ends: a command-line tool, a terminal UI built on\nTextual, and an MCP server that gives AI agents the same operations. Together\nthey fetch our domain inventory from registrars, price it, and build this\nwebsite.\n\nAll three started slowly. `--help` on the CLI took about 1.3 seconds on a busy\ndevelopment Mac, because the CLI's main module imported nearly everything at\nmodule scope: the site generator, the registrar clients and the database\nlayer. Python 3.15 added explicit lazy imports\n([PEP 810](https://peps.python.org/pep-0810/)), so we used them. We also\nadopted the new built-in `frozendict`\n([PEP 814](https://peps.python.org/pep-0814/)) and documented the new sampling\nprofiler ([PEP 799](https://peps.python.org/pep-0799/)).\n\nThe work took six pull requests. This post covers what we measured, the safety\ngate we built before deferring anything, the places where a lazy import is not\nlazy, and the results, including the two entry points that improved much less\nthan the CLI.\n\n## Where the start-up time went\n\n`python -X importtime` prints how long each import takes, including the\nimports it triggers. On the CLI, the expensive chains all served work that\n`--help` never does:\n\nLargest import chains behind the CLI's --help before the change\n\n| Package loaded by `--help` | Cumulative ms | First reached through |\n| --- | --- | --- |\n| markdown-it | 694 | CLI → site generator → agent documentation |\n| httpx2 | 331 | CLI → DNS checker |\n| asyncio | 321 | CLI → configuration → credentials |\n| DuckDB | 241 | CLI → coupons → domain model → types |\n| rcssmin | 192 | CLI → site generator |\n| Jinja2 | 191 | CLI → site generator |\n| PyYAML | 146 | CLI → coupons → domain model → sale policy |\n\nThese figures come from one run at a load average of about 50. They are\ncumulative, so nested packages overlap.\n\nTo bound what deferral could save, we ran each entry point with\n`PYTHON_LAZY_IMPORTS=all`, which makes every import lazy. The output stayed\nbyte-identical. The CLI's `--help` fell from 2,230 ms to 474 ms, the TUI's\nfrom 3,615 ms to 209 ms, and importing the MCP server from 5,667 ms to\n1,682 ms. That run was at a load average of 140 to 240, so only the ratios\nmean anything.\n\n## Why we did not turn on global lazy mode\n\nGlobal mode is one switch, but we kept it out of production. Lifeguard, the\nanalyzer described below, found import-time effects that deferral could change\nin 160 of the 801 files in our package and its dependencies. One of them is\nour own configuration module, which fills `os.environ` from a `.env` file when\nit is imported. Everything that reads the environment afterwards depends on\nthat import running first.\n\nExplicit statements apply only where they are written, and reviewers see them:\n\n```\nfrom app import config  # fills os.environ at import, so it stays eager\n\nlazy from app import website\nlazy from app.clients import build_registrar\nlazy import app.valuation\n```\n\nModule names in the examples are simplified.\n\n## A gate decides which imports may be deferred\n\nA deferred import moves the target module's import-time work from start-up to\nfirst use. That is safe only if the work does not depend on anything that\nchanges in between. We did not want to judge that by eye for every statement,\nso the first pull request added a gate and no lazy statements.\n\nThe gate runs [Lifeguard](https://github.com/facebook/Lifeguard), Meta's static\nanalyzer for lazy-import safety, pinned at version 0.7.0. Lifeguard reports\nwhich modules have import-time effects, which must load their imports eagerly,\nand which form import cycles. The gate then finds every `lazy` statement with\n`ast` and checks five rules:\n\n1. The importing module must not be one that Lifeguard says must load\n   eagerly, such as a module that writes to `sys.modules`.\n2. The target must have no import-time effects that deferral could change,\n   unless an allowlist entry vouches for that exact pair.\n3. The target must not be one of the importer's own eager dependencies: an\n   unsafe module it uses, a submodule it reaches only by attribute, or a\n   member of an import cycle it enters.\n4. An importer that has effects of its own must not defer a module in its own\n   import cycle.\n5. The configuration module is never deferred. No allowlist entry can\n   override this rule.\n\nThe gate fails closed. It fails if it scans no files, if Lifeguard exits with\nan error, if Lifeguard's report names none of our modules, or if an allowlist\nentry matches no lazy statement. A commit hook runs it whenever a Python file\nin the package, the allowlist or the lock file changes, because any edit can\ngive a module a new import-time effect. One Lifeguard run over our package and\nits dependencies took 8.4 seconds.\n\nRule 1 needed a code change first. The CLI's main module loaded a deployment\nscript by path and registered it in `sys.modules`, so Lifeguard required the\nwhole module to load eagerly. Moving that loader into a small helper module\nmade the CLI eligible.\n\n### The allowlist records each target's effects\n\nThe heaviest modules on our chains were unsafe, because each reads packaged\ntemplates or word lists when imported. Deferring one takes an allowlist entry\nwith a reason and the target's current effects:\n\n```\n[[allow]]\nimporter = \"app.cli.main\"\ntarget = \"app.direct_sale\"\nreason = \"At import it only builds an importlib.resources path to its packaged agreement templates, which does not depend on the working directory, the environment or sys.path. The templates are read later, inside functions.\"\neffects = [\"UnsafeMethodCall importlib.resources.abc.Traversable.joinpath\"]\n```\n\nThe reason has to explain why the effects can run later. In particular, they\nmust not depend on state that a command changes after start-up, such as the\nworking directory, environment variables or `sys.path`. A deferred module's\nimport errors also move from start-up to first use, and the reason has to\naccept that.\n\n`effects` lists Lifeguard's findings for the target, without line numbers. If\nthe list changes, the gate fails and prints the new one. That check caught a\nreal change. Another pull request, merged while the CLI change was in review,\nmade the site generator build a set from another module's table at import. On\nthe rebase, Lifeguard reported two new effects for the site generator and the\ngate refused the old entry. We confirmed that the reason still held and\nrecorded the new effects.\n\nLifeguard does not see everything. A probe module that only called `print` was\nreported as eligible. The gate enforces the analyzer's model, and a reviewer\nstill reads every new lazy statement. Today the gate checks 59 lazy statements\nin four files, with 8 allowlist entries.\n\n## Tests run our lazy statements eagerly\n\nA lazy `from m import f` binds `f` when the importing module first uses it,\nnot when the module loads. If a test patches `m.f` before that first use, the\nimporter keeps the mock after the patch ends:\n\n```\n# user.py\nlazy from src import f\n\ndef call():\n    return f()\n```\n\n```\nfrom unittest import mock\n\nimport user  # src has not been imported yet\n\nwith mock.patch(\"src.f\", lambda: \"mock\"):\n    print(user.call())  # mock: the first use binds f to the patch\nprint(user.call())      # still mock after the patch is undone\n```\n\nThat is what Python 3.15.2 printed for us. A lazy `import m` avoids the\nproblem, because each call looks up `m.f`. Switching to that form would have\nrenamed every call site, though, and our CLI tests patch names on the CLI\npackage itself, a contract we keep on purpose.\n\nSo the test process makes our own lazy statements eager. In 3.15.2,\n`PYTHON_LAZY_IMPORTS` and `-X lazy_imports` accept only `all` and `normal`,\nand neither makes an explicit `lazy` statement eager.\n`sys.set_lazy_imports_filter` can: a filter that returns `False` loads the\nimport at once.\n\n```\n# conftest.py, before the package is imported\nimport sys\n\ndef eager_in_package(importer: str, name: str, fromlist: object = None) -> bool:\n    return not (importer == \"app\" or importer.startswith(\"app.\"))\n\nsys.set_lazy_imports_filter(eager_in_package)\n```\n\nIn-process tests then see the old import timing and patch behavior. The lazy\npath gets its own checks. Subprocess tests start the real entry points\nwithout the filter and assert which packages `--help` must not load, and the\ngate checks every statement statically.\n\nWe also ran the whole suite once without the filter, through a one-off pytest\nplugin. Both runs passed 14,342 tests. Every failure in either run also failed\non the base commit, passed when rerun alone, or was the filter's own\nself-test, which must fail without the filter. No test failed from patch\ncapture.\n\n## Places where a lazy import is not lazy\n\nA lazy binding resolves the first time code looks up the name. Some lookups\nhappen while the module itself loads, which quietly undoes the deferral:\n\n- **Module-level tables.** The CLI kept dictionaries that mapped registrar\n  and appraisal-source names to factory functions. Building a dictionary\n  looked up every factory, which imported the clients package at start-up.\n- **Default argument values.** Three MCP tools take a default value from the\n  clients package. Python evaluates defaults when it creates the function, so\n  registering those tools imports the clients package anyway, and with it\n  DuckDB, httpx2 and PyYAML.\n- **Base classes.** The TUI's application class subclasses Textual's `App`,\n  so Textual has to load before the class body runs.\n- **`try` blocks.** `lazy` inside `try` is a syntax error (\"lazy import not\n  allowed inside try/except blocks\"), as it is inside a function. Both Textual\n  and FastMCP were imported inside `try` blocks.\n\nThe tables were the easy case. Each value now looks the factory up when it is\ncalled:\n\n```\nlazy from app.clients import build_escrow, build_mailer\n\n# Looks up both names, importing app.clients, when this module loads:\nCLIENT_BUILDERS = {\"escrow\": build_escrow, \"mailer\": build_mailer}\n\n# Looks up each name only when a command builds that client:\nCLIENT_BUILDERS = {\"escrow\": lambda: build_escrow(), \"mailer\": lambda: build_mailer()}\n```\n\nThe TUI work added one more rule: defer only what would not load anyway. The\nTUI's constants module builds a color table from the registrar list at import,\nwhich loads the clients package, the database layer and DuckDB. Deferring\nthose modules in the TUI's main module would only move a binding and add\nallowlist entries, so they stay eager.\n\n## Results\n\nEach figure is the median of nine runs. We made ten runs per side, alternating\nbetween the old and new code in one session, and discarded the first. The\nmachine was an Apple silicon development Mac running other work, so each row\nlists the load average during its runs. Both `--help` outputs were\nbyte-identical before and after.\n\nStart-up before and after explicit lazy imports\n\n| Process | Modules loaded | Median time | Load average |\n| --- | --- | --- | --- |\n| CLI `--help` | 664 → 308 | 1,314 ms → 326 ms | 70–85 |\n| TUI `--help` | 797 → 620 | 1,768 ms → 1,406 ms | 21–30 |\n| Importing the MCP server | 1,224 → 1,055 | 3,341 ms → 2,827 ms | 47–80 |\n\nThe CLI's `--help` became four times faster. It no longer loads DuckDB,\nJinja2, markdown-it, PyYAML, httpx2 or rcssmin, and a subprocess test pins\nthat list, so an import that brings one back fails the suite.\n\nThe TUI improved by 20 percent and the MCP server by 15 percent; the MCP\nserver registered the same 94 tools both ways. Most of what remains is\nTextual or FastMCP themselves, plus the clients chain described above.\nRemoving it would mean restructuring the entry points and the clients\npackage, not adding more `lazy` keywords.\n\nWe left two smaller costs in place. `asyncio` still loads at `--help`, because\nthe configuration module imports the credentials module, which imports\n`asyncio`; changing that means changing how the credentials module avoids an\nimport cycle. `rich.progress` costs about 71 ms, but an allowlist entry for a\nthird-party module would fail the gate whenever that library's import-time\neffects change.\n\nWe added no run-time switch to turn the lazy statements off. Rollback is a\nrevert.\n\n## frozendict\n\nPython 3.15 also added a built-in immutable mapping, `frozendict`. It is\nhashable, it is a `Mapping`, and it works with `json`, `pickle` and `copy`. It\nis not a subclass of `dict`.\n\nWe replaced our three `MappingProxyType` constants with `frozendict` and made\nit the rule for new constant mappings:\n\n```\nfrom collections.abc import Mapping\n\nSTATUS_LABELS: Mapping[str, str] = frozendict({  # pyrefly: ignore[bad-argument-count]\n    \"active\": \"For sale\",\n    \"sold\": \"Sold\",\n})\n```\n\nWe did not convert the 121 module-level `dict` constants we already had. The\ncode has about 530 `isinstance(x, dict)` checks, and a `frozendict` fails every\none of them.\n\nTwo tools needed attention. Under a Python 3.15 target, pyrefly 1.4.0 and\n1.4.1 type `frozendict.__init__` with no parameters, so every constructor\ncall with an argument is an error. The 1.5.0.dev1 pre-release accepts them. We\nstayed on the stable release, added the targeted ignore shown above, and will\nremove those ignores with `pyrefly suppress --remove-unused-ignores` after we\nupgrade. Ruff and ty accepted the code as written.\n\nOur change-based test selection fingerprints module-level values to spot state\nthat tests share. It read a `frozendict` as unknown, so we taught it to read\nthe members through the built-in type's own `items`. Code review then pointed\nout that a `frozendict` subclass can carry mutable attributes, so only the\nexact type takes that path.\n\n## The sampling profiler\n\nPython 3.15 ships a sampling profiler as `python -m profiling.sampling`. It\nreads a process's stacks at intervals without instrumenting the code. It can\n`attach` to a running process, `dump` its current stacks, `replay` a saved\ncapture into another format, or `run` a program from its first line.\n\nOn macOS, reading another process's memory requires elevated permissions;\nwithout them, the profiler stops with \"Unable to access process memory on\nmacOS\". The first draft of\nour how-to ran the CLI under `sudo` with `run`. Review caught that `run`\nstarts its target without dropping privileges, so the database, output files\nand `__pycache__` would have become root-owned. The documented pattern starts\nthe program as yourself and gives `sudo` to the profiler alone:\n\n```\nuv run my-tui\n# In a second terminal:\nsudo -E .venv/bin/python -m profiling.sampling attach --flamegraph -o profile.html \"$(pgrep -n -f my-tui)\"\nsudo chown \"$USER\" profile.html\n```\n\nUse the project's interpreter, because System Integrity Protection may block\nthe system Python. We have not used the profiler on this code yet. For\nstart-up, `-X importtime` answers the question more directly: what loads, and\nthrough which chain.\n\n## What we left out\n\nSome 3.15 additions did not earn a change:\n\n- **Sentinel values (PEP 661) and unpacking in comprehensions (PEP 798):**\n  rewriting two sentinels and 38 flattening comprehensions would change\n  nothing that a reader or a user notices.\n- **Closed `TypedDict` (PEP 728):** a typing change that is best made when\n  each of our 15 classes next changes.\n- **TOML 1.1:** other tools read the same files and do not support it.\n- **base64's new padding options:** checkout links that already sit in\n  buyers' inboxes must keep decoding exactly as before.\n\n## Try it on your own code\n\nStart with the measurement. Sort this output by its cumulative column and read\nthe chains behind the largest entries:\n\n```\npython -X importtime -m yourapp --help 2> importtime.txt\n```\n\nThen ask Lifeguard which modules are safe to defer. Its JSON report lists the\nmodules that may be deferred (`LAZY_ELIGIBLE`) and those that must load their\nimports eagerly (`LOAD_IMPORTS_EAGERLY`):\n\n```\nuvx --from lifeguard-lazy-imports==0.7.0 lifeguard run-tree src/yourapp report.json --python-version 3.15\n```\n\nPass `--site-packages` so that it can follow your dependencies. Lifeguard did\nnot follow a symlinked package for us, so our gate copies the package's\nsource into a temporary tree first.\n\nBefore you add the first `lazy from`, search your tests for patches of the\nnames you plan to defer. A filter like the one above keeps those tests honest,\nand subprocess tests keep the lazy path honest.\n","body_html":"<h1 id=\"adopting-python-3-15-s-lazy-imports-a-4-faster-cli-and-where-the\">Adopting Python 3.15&#39;s lazy imports: a 4× faster CLI, and where they didn&#39;t help</h1>\n<p>November 8, 2026\n<a href=\"https://namegarage.com/blog/category/engineering\" rel=\"nofollow ugc noopener\">Dev blog</a><a href=\"https://namegarage.com/blog/tag/python\" rel=\"nofollow ugc noopener\">#python</a><a href=\"https://namegarage.com/blog/tag/performance\" rel=\"nofollow ugc noopener\">#performance</a><a href=\"https://namegarage.com/blog/tag/developer-tools\" rel=\"nofollow ugc noopener\">#developer-tools</a></p>\n<p>On November 3 we moved our back office to Python 3.15.2. It is one Python\npackage with three front ends: a command-line tool, a terminal UI built on\nTextual, and an MCP server that gives AI agents the same operations. Together\nthey fetch our domain inventory from registrars, price it, and build this\nwebsite.</p>\n<p>All three started slowly. <code>--help</code> on the CLI took about 1.3 seconds on a busy\ndevelopment Mac, because the CLI&#39;s main module imported nearly everything at\nmodule scope: the site generator, the registrar clients and the database\nlayer. Python 3.15 added explicit lazy imports\n(<a href=\"https://peps.python.org/pep-0810/\" rel=\"nofollow ugc noopener\">PEP 810</a>), so we used them. We also\nadopted the new built-in <code>frozendict</code>\n(<a href=\"https://peps.python.org/pep-0814/\" rel=\"nofollow ugc noopener\">PEP 814</a>) and documented the new sampling\nprofiler (<a href=\"https://peps.python.org/pep-0799/\" rel=\"nofollow ugc noopener\">PEP 799</a>).</p>\n<p>The work took six pull requests. This post covers what we measured, the safety\ngate we built before deferring anything, the places where a lazy import is not\nlazy, and the results, including the two entry points that improved much less\nthan the CLI.</p>\n<h2 id=\"where-the-start-up-time-went\">Where the start-up time went</h2>\n<p><code>python -X importtime</code> prints how long each import takes, including the\nimports it triggers. On the CLI, the expensive chains all served work that\n<code>--help</code> never does:</p>\n<p>Largest import chains behind the CLI&#39;s --help before the change</p>\n<div class=\"table-wrap\"><table><thead><tr><th>Package loaded by <code>--help</code></th><th>Cumulative ms</th><th>First reached through</th></tr></thead><tbody><tr><td>markdown-it</td><td>694</td><td>CLI → site generator → agent documentation</td></tr><tr><td>httpx2</td><td>331</td><td>CLI → DNS checker</td></tr><tr><td>asyncio</td><td>321</td><td>CLI → configuration → credentials</td></tr><tr><td>DuckDB</td><td>241</td><td>CLI → coupons → domain model → types</td></tr><tr><td>rcssmin</td><td>192</td><td>CLI → site generator</td></tr><tr><td>Jinja2</td><td>191</td><td>CLI → site generator</td></tr><tr><td>PyYAML</td><td>146</td><td>CLI → coupons → domain model → sale policy</td></tr></tbody></table></div>\n<p>These figures come from one run at a load average of about 50. They are\ncumulative, so nested packages overlap.</p>\n<p>To bound what deferral could save, we ran each entry point with\n<code>PYTHON_LAZY_IMPORTS=all</code>, which makes every import lazy. The output stayed\nbyte-identical. The CLI&#39;s <code>--help</code> fell from 2,230 ms to 474 ms, the TUI&#39;s\nfrom 3,615 ms to 209 ms, and importing the MCP server from 5,667 ms to\n1,682 ms. That run was at a load average of 140 to 240, so only the ratios\nmean anything.</p>\n<h2 id=\"why-we-did-not-turn-on-global-lazy-mode\">Why we did not turn on global lazy mode</h2>\n<p>Global mode is one switch, but we kept it out of production. Lifeguard, the\nanalyzer described below, found import-time effects that deferral could change\nin 160 of the 801 files in our package and its dependencies. One of them is\nour own configuration module, which fills <code>os.environ</code> from a <code>.env</code> file when\nit is imported. Everything that reads the environment afterwards depends on\nthat import running first.</p>\n<p>Explicit statements apply only where they are written, and reviewers see them:</p>\n<pre><code>from app import config  # fills os.environ at import, so it stays eager\n\nlazy from app import website\nlazy from app.clients import build_registrar\nlazy import app.valuation</code></pre>\n<p>Module names in the examples are simplified.</p>\n<h2 id=\"a-gate-decides-which-imports-may-be-deferred\">A gate decides which imports may be deferred</h2>\n<p>A deferred import moves the target module&#39;s import-time work from start-up to\nfirst use. That is safe only if the work does not depend on anything that\nchanges in between. We did not want to judge that by eye for every statement,\nso the first pull request added a gate and no lazy statements.</p>\n<p>The gate runs <a href=\"https://github.com/facebook/Lifeguard\" rel=\"nofollow ugc noopener\">Lifeguard</a>, Meta&#39;s static\nanalyzer for lazy-import safety, pinned at version 0.7.0. Lifeguard reports\nwhich modules have import-time effects, which must load their imports eagerly,\nand which form import cycles. The gate then finds every <code>lazy</code> statement with\n<code>ast</code> and checks five rules:</p>\n<ol><li><p>The importing module must not be one that Lifeguard says must load</p><p> eagerly, such as a module that writes to <code>sys.modules</code>.</p></li><li><p>The target must have no import-time effects that deferral could change,</p><p> unless an allowlist entry vouches for that exact pair.</p></li><li><p>The target must not be one of the importer&#39;s own eager dependencies: an</p><p> unsafe module it uses, a submodule it reaches only by attribute, or a\n member of an import cycle it enters.</p></li><li><p>An importer that has effects of its own must not defer a module in its own</p><p> import cycle.</p></li><li><p>The configuration module is never deferred. No allowlist entry can</p><p> override this rule.</p></li></ol>\n<p>The gate fails closed. It fails if it scans no files, if Lifeguard exits with\nan error, if Lifeguard&#39;s report names none of our modules, or if an allowlist\nentry matches no lazy statement. A commit hook runs it whenever a Python file\nin the package, the allowlist or the lock file changes, because any edit can\ngive a module a new import-time effect. One Lifeguard run over our package and\nits dependencies took 8.4 seconds.</p>\n<p>Rule 1 needed a code change first. The CLI&#39;s main module loaded a deployment\nscript by path and registered it in <code>sys.modules</code>, so Lifeguard required the\nwhole module to load eagerly. Moving that loader into a small helper module\nmade the CLI eligible.</p>\n<h3 id=\"the-allowlist-records-each-target-s-effects\">The allowlist records each target&#39;s effects</h3>\n<p>The heaviest modules on our chains were unsafe, because each reads packaged\ntemplates or word lists when imported. Deferring one takes an allowlist entry\nwith a reason and the target&#39;s current effects:</p>\n<pre><code>[[allow]]\nimporter = &quot;app.cli.main&quot;\ntarget = &quot;app.direct_sale&quot;\nreason = &quot;At import it only builds an importlib.resources path to its packaged agreement templates, which does not depend on the working directory, the environment or sys.path. The templates are read later, inside functions.&quot;\neffects = [&quot;UnsafeMethodCall importlib.resources.abc.Traversable.joinpath&quot;]</code></pre>\n<p>The reason has to explain why the effects can run later. In particular, they\nmust not depend on state that a command changes after start-up, such as the\nworking directory, environment variables or <code>sys.path</code>. A deferred module&#39;s\nimport errors also move from start-up to first use, and the reason has to\naccept that.</p>\n<p><code>effects</code> lists Lifeguard&#39;s findings for the target, without line numbers. If\nthe list changes, the gate fails and prints the new one. That check caught a\nreal change. Another pull request, merged while the CLI change was in review,\nmade the site generator build a set from another module&#39;s table at import. On\nthe rebase, Lifeguard reported two new effects for the site generator and the\ngate refused the old entry. We confirmed that the reason still held and\nrecorded the new effects.</p>\n<p>Lifeguard does not see everything. A probe module that only called <code>print</code> was\nreported as eligible. The gate enforces the analyzer&#39;s model, and a reviewer\nstill reads every new lazy statement. Today the gate checks 59 lazy statements\nin four files, with 8 allowlist entries.</p>\n<h2 id=\"tests-run-our-lazy-statements-eagerly\">Tests run our lazy statements eagerly</h2>\n<p>A lazy <code>from m import f</code> binds <code>f</code> when the importing module first uses it,\nnot when the module loads. If a test patches <code>m.f</code> before that first use, the\nimporter keeps the mock after the patch ends:</p>\n<pre><code># user.py\nlazy from src import f\n\ndef call():\n    return f()</code></pre>\n<pre><code>from unittest import mock\n\nimport user  # src has not been imported yet\n\nwith mock.patch(&quot;src.f&quot;, lambda: &quot;mock&quot;):\n    print(user.call())  # mock: the first use binds f to the patch\nprint(user.call())      # still mock after the patch is undone</code></pre>\n<p>That is what Python 3.15.2 printed for us. A lazy <code>import m</code> avoids the\nproblem, because each call looks up <code>m.f</code>. Switching to that form would have\nrenamed every call site, though, and our CLI tests patch names on the CLI\npackage itself, a contract we keep on purpose.</p>\n<p>So the test process makes our own lazy statements eager. In 3.15.2,\n<code>PYTHON_LAZY_IMPORTS</code> and <code>-X lazy_imports</code> accept only <code>all</code> and <code>normal</code>,\nand neither makes an explicit <code>lazy</code> statement eager.\n<code>sys.set_lazy_imports_filter</code> can: a filter that returns <code>False</code> loads the\nimport at once.</p>\n<pre><code># conftest.py, before the package is imported\nimport sys\n\ndef eager_in_package(importer: str, name: str, fromlist: object = None) -&gt; bool:\n    return not (importer == &quot;app&quot; or importer.startswith(&quot;app.&quot;))\n\nsys.set_lazy_imports_filter(eager_in_package)</code></pre>\n<p>In-process tests then see the old import timing and patch behavior. The lazy\npath gets its own checks. Subprocess tests start the real entry points\nwithout the filter and assert which packages <code>--help</code> must not load, and the\ngate checks every statement statically.</p>\n<p>We also ran the whole suite once without the filter, through a one-off pytest\nplugin. Both runs passed 14,342 tests. Every failure in either run also failed\non the base commit, passed when rerun alone, or was the filter&#39;s own\nself-test, which must fail without the filter. No test failed from patch\ncapture.</p>\n<h2 id=\"places-where-a-lazy-import-is-not-lazy\">Places where a lazy import is not lazy</h2>\n<p>A lazy binding resolves the first time code looks up the name. Some lookups\nhappen while the module itself loads, which quietly undoes the deferral:</p>\n<ul><li><p><strong>Module-level tables.</strong> The CLI kept dictionaries that mapped registrar</p><p>and appraisal-source names to factory functions. Building a dictionary\nlooked up every factory, which imported the clients package at start-up.</p></li><li><p><strong>Default argument values.</strong> Three MCP tools take a default value from the</p><p>clients package. Python evaluates defaults when it creates the function, so\nregistering those tools imports the clients package anyway, and with it\nDuckDB, httpx2 and PyYAML.</p></li><li><p><strong>Base classes.</strong> The TUI&#39;s application class subclasses Textual&#39;s <code>App</code>,</p><p>so Textual has to load before the class body runs.</p></li><li><p><strong><code>try</code> blocks.</strong> <code>lazy</code> inside <code>try</code> is a syntax error (&quot;lazy import not</p><p>allowed inside try/except blocks&quot;), as it is inside a function. Both Textual\nand FastMCP were imported inside <code>try</code> blocks.</p></li></ul>\n<p>The tables were the easy case. Each value now looks the factory up when it is\ncalled:</p>\n<pre><code>lazy from app.clients import build_escrow, build_mailer\n\n# Looks up both names, importing app.clients, when this module loads:\nCLIENT_BUILDERS = {&quot;escrow&quot;: build_escrow, &quot;mailer&quot;: build_mailer}\n\n# Looks up each name only when a command builds that client:\nCLIENT_BUILDERS = {&quot;escrow&quot;: lambda: build_escrow(), &quot;mailer&quot;: lambda: build_mailer()}</code></pre>\n<p>The TUI work added one more rule: defer only what would not load anyway. The\nTUI&#39;s constants module builds a color table from the registrar list at import,\nwhich loads the clients package, the database layer and DuckDB. Deferring\nthose modules in the TUI&#39;s main module would only move a binding and add\nallowlist entries, so they stay eager.</p>\n<h2 id=\"results\">Results</h2>\n<p>Each figure is the median of nine runs. We made ten runs per side, alternating\nbetween the old and new code in one session, and discarded the first. The\nmachine was an Apple silicon development Mac running other work, so each row\nlists the load average during its runs. Both <code>--help</code> outputs were\nbyte-identical before and after.</p>\n<p>Start-up before and after explicit lazy imports</p>\n<div class=\"table-wrap\"><table><thead><tr><th>Process</th><th>Modules loaded</th><th>Median time</th><th>Load average</th></tr></thead><tbody><tr><td>CLI <code>--help</code></td><td>664 → 308</td><td>1,314 ms → 326 ms</td><td>70–85</td></tr><tr><td>TUI <code>--help</code></td><td>797 → 620</td><td>1,768 ms → 1,406 ms</td><td>21–30</td></tr><tr><td>Importing the MCP server</td><td>1,224 → 1,055</td><td>3,341 ms → 2,827 ms</td><td>47–80</td></tr></tbody></table></div>\n<p>The CLI&#39;s <code>--help</code> became four times faster. It no longer loads DuckDB,\nJinja2, markdown-it, PyYAML, httpx2 or rcssmin, and a subprocess test pins\nthat list, so an import that brings one back fails the suite.</p>\n<p>The TUI improved by 20 percent and the MCP server by 15 percent; the MCP\nserver registered the same 94 tools both ways. Most of what remains is\nTextual or FastMCP themselves, plus the clients chain described above.\nRemoving it would mean restructuring the entry points and the clients\npackage, not adding more <code>lazy</code> keywords.</p>\n<p>We left two smaller costs in place. <code>asyncio</code> still loads at <code>--help</code>, because\nthe configuration module imports the credentials module, which imports\n<code>asyncio</code>; changing that means changing how the credentials module avoids an\nimport cycle. <code>rich.progress</code> costs about 71 ms, but an allowlist entry for a\nthird-party module would fail the gate whenever that library&#39;s import-time\neffects change.</p>\n<p>We added no run-time switch to turn the lazy statements off. Rollback is a\nrevert.</p>\n<h2 id=\"frozendict\">frozendict</h2>\n<p>Python 3.15 also added a built-in immutable mapping, <code>frozendict</code>. It is\nhashable, it is a <code>Mapping</code>, and it works with <code>json</code>, <code>pickle</code> and <code>copy</code>. It\nis not a subclass of <code>dict</code>.</p>\n<p>We replaced our three <code>MappingProxyType</code> constants with <code>frozendict</code> and made\nit the rule for new constant mappings:</p>\n<pre><code>from collections.abc import Mapping\n\nSTATUS_LABELS: Mapping[str, str] = frozendict({  # pyrefly: ignore[bad-argument-count]\n    &quot;active&quot;: &quot;For sale&quot;,\n    &quot;sold&quot;: &quot;Sold&quot;,\n})</code></pre>\n<p>We did not convert the 121 module-level <code>dict</code> constants we already had. The\ncode has about 530 <code>isinstance(x, dict)</code> checks, and a <code>frozendict</code> fails every\none of them.</p>\n<p>Two tools needed attention. Under a Python 3.15 target, pyrefly 1.4.0 and\n1.4.1 type <code>frozendict.__init__</code> with no parameters, so every constructor\ncall with an argument is an error. The 1.5.0.dev1 pre-release accepts them. We\nstayed on the stable release, added the targeted ignore shown above, and will\nremove those ignores with <code>pyrefly suppress --remove-unused-ignores</code> after we\nupgrade. Ruff and ty accepted the code as written.</p>\n<p>Our change-based test selection fingerprints module-level values to spot state\nthat tests share. It read a <code>frozendict</code> as unknown, so we taught it to read\nthe members through the built-in type&#39;s own <code>items</code>. Code review then pointed\nout that a <code>frozendict</code> subclass can carry mutable attributes, so only the\nexact type takes that path.</p>\n<h2 id=\"the-sampling-profiler\">The sampling profiler</h2>\n<p>Python 3.15 ships a sampling profiler as <code>python -m profiling.sampling</code>. It\nreads a process&#39;s stacks at intervals without instrumenting the code. It can\n<code>attach</code> to a running process, <code>dump</code> its current stacks, <code>replay</code> a saved\ncapture into another format, or <code>run</code> a program from its first line.</p>\n<p>On macOS, reading another process&#39;s memory requires elevated permissions;\nwithout them, the profiler stops with &quot;Unable to access process memory on\nmacOS&quot;. The first draft of\nour how-to ran the CLI under <code>sudo</code> with <code>run</code>. Review caught that <code>run</code>\nstarts its target without dropping privileges, so the database, output files\nand <code>__pycache__</code> would have become root-owned. The documented pattern starts\nthe program as yourself and gives <code>sudo</code> to the profiler alone:</p>\n<pre><code>uv run my-tui\n# In a second terminal:\nsudo -E .venv/bin/python -m profiling.sampling attach --flamegraph -o profile.html &quot;$(pgrep -n -f my-tui)&quot;\nsudo chown &quot;$USER&quot; profile.html</code></pre>\n<p>Use the project&#39;s interpreter, because System Integrity Protection may block\nthe system Python. We have not used the profiler on this code yet. For\nstart-up, <code>-X importtime</code> answers the question more directly: what loads, and\nthrough which chain.</p>\n<h2 id=\"what-we-left-out\">What we left out</h2>\n<p>Some 3.15 additions did not earn a change:</p>\n<ul><li><p><strong>Sentinel values (PEP 661) and unpacking in comprehensions (PEP 798):</strong></p><p>rewriting two sentinels and 38 flattening comprehensions would change\nnothing that a reader or a user notices.</p></li><li><p><strong>Closed <code>TypedDict</code> (PEP 728):</strong> a typing change that is best made when</p><p>each of our 15 classes next changes.</p></li><li><strong>TOML 1.1:</strong> other tools read the same files and do not support it.</li><li><p><strong>base64&#39;s new padding options:</strong> checkout links that already sit in</p><p>buyers&#39; inboxes must keep decoding exactly as before.</p></li></ul>\n<h2 id=\"try-it-on-your-own-code\">Try it on your own code</h2>\n<p>Start with the measurement. Sort this output by its cumulative column and read\nthe chains behind the largest entries:</p>\n<pre><code>python -X importtime -m yourapp --help 2&gt; importtime.txt</code></pre>\n<p>Then ask Lifeguard which modules are safe to defer. Its JSON report lists the\nmodules that may be deferred (<code>LAZY_ELIGIBLE</code>) and those that must load their\nimports eagerly (<code>LOAD_IMPORTS_EAGERLY</code>):</p>\n<pre><code>uvx --from lifeguard-lazy-imports==0.7.0 lifeguard run-tree src/yourapp report.json --python-version 3.15</code></pre>\n<p>Pass <code>--site-packages</code> so that it can follow your dependencies. Lifeguard did\nnot follow a symlinked package for us, so our gate copies the package&#39;s\nsource into a temporary tree first.</p>\n<p>Before you add the first <code>lazy from</code>, search your tests for patches of the\nnames you plan to defer. A filter like the one above keeps those tests honest,\nand subprocess tests keep the lazy path honest.</p>","headings":[{"level":1,"text":"Adopting Python 3.15's lazy imports: a 4× faster CLI, and where they didn't help","id":"adopting-python-3-15-s-lazy-imports-a-4-faster-cli-and-where-the"},{"level":2,"text":"Where the start-up time went","id":"where-the-start-up-time-went"},{"level":2,"text":"Why we did not turn on global lazy mode","id":"why-we-did-not-turn-on-global-lazy-mode"},{"level":2,"text":"A gate decides which imports may be deferred","id":"a-gate-decides-which-imports-may-be-deferred"},{"level":3,"text":"The allowlist records each target's effects","id":"the-allowlist-records-each-target-s-effects"},{"level":2,"text":"Tests run our lazy statements eagerly","id":"tests-run-our-lazy-statements-eagerly"},{"level":2,"text":"Places where a lazy import is not lazy","id":"places-where-a-lazy-import-is-not-lazy"},{"level":2,"text":"Results","id":"results"},{"level":2,"text":"frozendict","id":"frozendict"},{"level":2,"text":"The sampling profiler","id":"the-sampling-profiler"},{"level":2,"text":"What we left out","id":"what-we-left-out"},{"level":2,"text":"Try it on your own code","id":"try-it-on-your-own-code"}]}}