From 62c95b167fad3ced856c1fd6ea8ca9706afd7e7a Mon Sep 17 00:00:00 2001 From: Anton Darahan Date: Mon, 30 Nov 2026 21:10:58 +0000 Subject: [PATCH] gh-162846: Fix `test_compileall` with `PYTHONDONTWRITEBYTECODE` or `PYTHONOPTIMIZE` set (GH-162847) (cherry picked from commit a3947124f3dad907152395aa238ee4b99d7539b8) Co-authored-by: Anton Darahan Co-authored-by: Stan Ulbrych --- Lib/test/test_compileall.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Lib/test/test_compileall.py b/Lib/test/test_compileall.py index e9caa82a700d2fe..ab0be90c92ca2d7 100644 --- a/Lib/test/test_compileall.py +++ b/Lib/test/test_compileall.py @@ -1154,10 +1154,16 @@ def test_import(self): # Change of the module content script = self.make_script("print(0)", name="module") - # Import the module in Python with -O (optimization level 1) - script_helper.assert_python_ok( - "-O", "-c", "import module", __isolated=False, PYTHONPATH=self.path - ) + # Import the module in Python with -O (optimization level 1). + # The child must write the opt-1 pyc file, so ignore any ambient + # PYTHONDONTWRITEBYTECODE or PYTHONOPTIMIZE. + with os_helper.EnvironmentVarGuard() as env: + env.unset('PYTHONDONTWRITEBYTECODE') + env.unset('PYTHONOPTIMIZE') + script_helper.assert_python_ok( + "-O", "-c", "import module", + __isolated=False, PYTHONPATH=self.path + ) # Only opt-1.pyc is changed self.assertEqual(inode, os.stat(pycs[0]).st_ino)