Skip to content

Commit bc9163e

Browse files
committed
gh-162710: forward optimize level in PyZipFile.writepy()
_get_code() compiled with the builder interpreter's optimization level instead of the level requested via PyZipFile(optimize=...). Pass _optimize through to source_to_code() so archived bytecode matches the requested level. Add a regression test.
1 parent 5dbe2ac commit bc9163e

3 files changed

Lines changed: 32 additions & 1 deletion

File tree

‎Lib/test/test_zipfile/test_core.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3697,6 +3697,35 @@ def test_write_with_optimization(self):
36973697
self.assertIn('email/__init__' + ext, names)
36983698
self.assertIn('email/mime/text' + ext, names)
36993699

3700+
def test_write_with_optimization_level(self):
3701+
# gh-162710: writepy() must compile with the requested optimization
3702+
# level even when it differs from the builder interpreter's level.
3703+
source = (
3704+
'"""module docs"""\n'
3705+
'DEBUG = __debug__\n'
3706+
)
3707+
with temp_cwd(None):
3708+
with open(TESTFN, "w", encoding="utf-8") as f:
3709+
f.write(source)
3710+
archive = TESTFN + ".zip"
3711+
for level in (0, 1, 2):
3712+
with zipfile.PyZipFile(archive, "w", optimize=level) as zipfp:
3713+
zipfp.writepy(TESTFN)
3714+
path = archive + os.sep + os.path.basename(TESTFN) + "c"
3715+
ns = {}
3716+
with zipfile.ZipFile(archive) as zipfp:
3717+
exec(zipfp.read(os.path.basename(TESTFN) + "c"), ns)
3718+
if level == 0:
3719+
self.assertIs(ns["DEBUG"], True)
3720+
else:
3721+
self.assertIs(ns["DEBUG"], False)
3722+
if level == 2:
3723+
self.assertIsNone(ns["__doc__"])
3724+
else:
3725+
self.assertEqual(ns["__doc__"], "module docs")
3726+
unlink(TESTFN)
3727+
unlink(archive)
3728+
37003729
def test_write_python_directory(self):
37013730
os.mkdir(TESTFN2)
37023731
try:

‎Lib/zipfile/__init__.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2911,7 +2911,8 @@ def _get_code(self, pathname, basename):
29112911
try:
29122912
if self.debug:
29132913
print("Compiling", file_py)
2914-
code = loader.source_to_code(source_bytes, archivename)
2914+
code = loader.source_to_code(source_bytes, archivename,
2915+
_optimize=self._optimize)
29152916
except Exception as err:
29162917
# Historically, this function prints messages here rather than raising
29172918
# (see test_zipfile.test_write_filtered_python_package)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix :meth:`zipfile.PyZipFile.writepy` to compile archived bytecode at the optimization level requested by the ``optimize`` argument rather than the builder interpreter's level.

0 commit comments

Comments
 (0)