Skip to content

PyZipFile.writepy() ignores the requested optimization level when compiling archived bytecode #162710

Backlog

Description

@limadog9

Bug report

Starting in Python 3.15, PyZipFile.writepy() compiles modules at the builder interpreter’s optimization level even when PyZipFile was given an explicit optimize argument. This changes the behavior of the distributed .pyc files.

Run this script with a normal interpreter (no -O or -OO):

from pathlib import Path
import sys
from tempfile import TemporaryDirectory
from zipfile import PyZipFile

with TemporaryDirectory() as tmp:
    src = Path(tmp, "archive_probe.py")
    src.write_text('"""module docs"""\nDEBUG = __debug__\n')
    archive = Path(tmp, "lib.zip")

    with PyZipFile(archive, "w", optimize=2) as zf:
        zf.writepy(src)
        assert zf.namelist() == ["archive_probe.pyc"]

    sys.path.insert(0, str(archive))
    import archive_probe
    print(archive_probe.DEBUG, archive_probe.__doc__)

Expected output, confirmed on 3.14.10: False None.

Actual output on 3.15.0, 3.15.2, 3.16.0a2, and main at 3b309372: True module docs.

The reverse case also affects deployed code. I built an archive under python -O with optimize=0, then imported it in a separate interpreter running without -O. An assert in the archived function had been compiled out. The same procedure on 3.14.10 preserved it.

I traced the change to a9b6788ae6f0 (#144293). PyZipFile stores the requested level in self._optimize, but _get_code() calls loader.source_to_code(source_bytes, archivename) without forwarding it. Passing _optimize=self._optimize locally produced the expected results for all four requested levels (-1, 0, 1, 2) under normal, -O, and -OO interpreters.

The existing test_write_with_optimization already requests a level different from the running interpreter. It checks the .pyc member names only. Checking the archived module’s __debug__ value would catch this regression.

CPython versions tested on:

3.15, 3.16, CPython main branch

Operating systems tested on:

Linux

Linked PRs

Activity

  1. added
    type-bug
    on Nov 27, 2026
  2. added
    stdlib
    on Nov 27, 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

    stdlibtype-bug

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions