Skip to content

gh-161644: Avoid unmarshalling zipped .pyc files twice on import - #161700

Open
itamaro wants to merge 4 commits into
python:mainfrom
itamaro:zipimport-pyc-header-only
Open

itamaro wants to merge 4 commits into
python:mainfrom
itamaro:zipimport-pyc-header-only

Conversation

@itamaro

@itamaro itamaro commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

zipimporter.get_filename() (and therefore find_spec()) read, decompressed and unmarshalled the whole .pyc just to determine the module's file name, and exec_module() then did it all again. Only the 16-byte header matters for picking the file: a bad or stale header falls back to the sibling .py, while errors in the marshalled body never do.

This splits the header checks out of _unmarshal_code() and has get_filename() run only those, reading (and for deflate/zstd members, decompressing) just enough of the member to cover the header.

Observable change: a .pyc with a valid header and a corrupt body now fails in exec_module() instead of find_spec(), with the same exception. GH-153799 made the equivalent change for a SyntaxError in source modules.

Benchmarks

Release build, Linux, warm page cache, timestamp-based pycs.

Importing 27 stdlib packages (148 modules) from a zip of ~350 stdlib modules with .pyc next to .py, min of 40 runs:

compression main this PR
stored 96 ms 79 ms −18%
deflate 131 ms 99 ms −25%
zstd 141 ms 125 ms −12%

Per module, find_spec() + get_code() for a single .pyc (in-process medians):

pyc size stored deflate zstd
10 KB −6% −1% −10%
50 KB −32% −30% −34%
500 KB −49% −46% −44%
5 MB −44% −41% −34%

find_spec() itself no longer scales with pyc size: ~0.1 ms regardless of size, versus 43 ms for a 5 MB pyc on main.

zstd gains less because ZstdDecompressor construction dominates small reads and zstd decodes a whole block before producing output.

`get_filename()` (and so `find_spec()`) read, decompressed and
unmarshalled the whole `.pyc` just to learn the file name, and
`exec_module()` then did it all again.  Only the 16-byte header matters
for picking the file: a bad or stale header falls back to the sibling
`.py`, while errors in the marshalled body never do.

Split the header checks out of `_unmarshal_code()` and have
`get_filename()` run only those, reading (and decompressing) just
enough of the member to cover the header.  A `.pyc` with a valid header
and a corrupt body now fails in `exec_module()` instead of
`find_spec()`, with the same exception.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@itamaro itamaro added performance Performance or resource usage stdlib Standard Library Python modules in the Lib/ directory topic-importlib labels Nov 9, 2026
@bedevere-app bedevere-app Bot added the type-feature A feature request or enhancement label Nov 9, 2026
@read-the-docs-community

read-the-docs-community Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #36150222 | 📁 Comparing b47531b against main (e3262d9)

  🔍 Preview build  

79 files changed · + 1 added · ± 78 modified

+ Added

± Modified

@itamaro
itamaro marked this pull request as ready for review November 9, 2026 20:57
Comment thread Lib/test/test_zipimport.py Outdated
m.loads.assert_called_once()
self.assertEqual(mod.get_file(), expected_path)

def test_corrupt_pyc_body_defers_to_exec(self):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't the test above help make sure the read is deferred? And do we need to state where the failure is picked up as much as making sure the exception is raised when going through all the steps for an import?

@itamaro itamaro Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

answering all the test-related comments:

all the new tests were related, for some definition of "related", but they were an overkill covering engineered edge cases, so I cut those you flagged as unrelated.

the "lazy imports" comments are also moot - gone with the deleted tests.

Doesn't the test above help make sure the read is deferred?

the tests had overlap, which is gone now. I kept test_corrupt_pyc_body_defers_to_exec to cover the read deferral.

And do we need to state where the failure is picked up as much as making sure the exception is raised when going through all the steps for an import?

I think so, this guards the invariant introduced here - no error raised until the exec.

Comment thread Lib/test/test_zipimport.py Resolved
Comment thread Lib/test/test_zipimport.py Resolved
Comment thread Lib/test/test_zipimport.py Resolved
Comment thread Lib/test/test_zipimport.py Resolved
Comment thread Lib/test/test_zipimport.py Resolved
Comment thread Lib/test/test_zipimport.py Resolved
Comment thread Lib/test/test_zipimport.py Resolved
Comment thread Lib/zipimport.py Outdated
except Exception:
if compress == _ZIP_DEFLATED:
raise
raise ZipImportError("could not decompress zstd data")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The globals list 4 decompression methods but this assumes only 2 and with a very direct fallthrough. Otherwise the comment for the globals is misleading.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I dropped the global constants. they were somewhat misleading. I thought they would improve readability by replacing the magic numbers with named constants, but it just made it less clear because I needed to replace match-case with if-else's. so I went back to match-case with literal values, and used the same pattern in _decompress_prefix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting core review performance Performance or resource usage stdlib Standard Library Python modules in the Lib/ directory topic-importlib type-feature A feature request or enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants