Skip to content

Commit 3f5491a

Browse files
gh-134300: Remove idlelib from the path of the IDLE user process (#152739)
The idlelib directory ends up on sys.path when idle.py is run as a script, and it was passed to the user process, where it let user code import idlelib submodules as top-level modules, such as "import help".
1 parent ea7619f commit 3f5491a

3 files changed

Lines changed: 24 additions & 0 deletions

File tree

Lib/idlelib/idle_test/test_pyshell.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
# Plus coverage of test_warning. Was 20% with test_openshell.
33

44
from idlelib import pyshell
5+
import os
56
import unittest
67
from test.support import requires
78
from tkinter import Tk
@@ -28,6 +29,14 @@ def test_restart_line_narrow(self):
2829
self.assertEqual(pyshell.restart_line(width, ''), expect)
2930
self.assertEqual(pyshell.restart_line(taglen+2, ''), expect+' =')
3031

32+
def test_fix_user_path(self):
33+
# gh-134300: the idlelib directory is removed, other entries kept.
34+
eq = self.assertEqual
35+
idlelib_dir = os.path.dirname(os.path.abspath(pyshell.__file__))
36+
eq(pyshell.fix_user_path(['', '/a', idlelib_dir, '/b']), ['', '/a', '/b'])
37+
eq(pyshell.fix_user_path(['/a', '/b']), ['/a', '/b'])
38+
eq(pyshell.fix_user_path([idlelib_dir]), [])
39+
3140

3241
class PyShellFileListTest(unittest.TestCase):
3342

Lib/idlelib/pyshell.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,17 @@ def restart_line(width, filename): # See bpo-38141.
408408
return tag[:-2] # Remove ' ='.
409409

410410

411+
def fix_user_path(path):
412+
"""Return path without the idlelib directory (gh-134300).
413+
414+
That directory is on sys.path when idle.py is run as a script.
415+
Otherwise user code could import idlelib submodules as top-level
416+
modules, such as "import help".
417+
"""
418+
idlelib_dir = os.path.dirname(os.path.abspath(__file__))
419+
return [p for p in path if p != idlelib_dir]
420+
421+
411422
class ModifiedInterpreter(InteractiveInterpreter):
412423

413424
def __init__(self, tkconsole):
@@ -568,6 +579,7 @@ def transfer_path(self, with_cwd=False):
568579
path.extend(sys.path)
569580
else:
570581
path = sys.path
582+
path = fix_user_path(path) # gh-134300
571583

572584
self.runcommand("""if 1:
573585
import sys as _sys
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Do not add the ``idlelib`` directory to the path of the IDLE user process.
2+
User code run in IDLE can no longer import ``idlelib`` submodules as
3+
top-level modules, such as ``import help``.

0 commit comments

Comments
 (0)