diff --git a/Lib/_pyrepl/_module_completer.py b/Lib/_pyrepl/_module_completer.py index bfc2868aa1dd81..e3ff55cdcd120f 100644 --- a/Lib/_pyrepl/_module_completer.py +++ b/Lib/_pyrepl/_module_completer.py @@ -362,9 +362,14 @@ def _remove_separated_words(self, line: str, completion: str) -> str: last_word = line.split(" ")[-1] if not last_word: return completion + if last_word.startswith("."): + offset = 0 + else: # Only match the start of module parts + last_word = f".{last_word}" + offset = 1 index = completion.rfind(last_word) if index > 0: - return completion[index:] + return completion[index + offset:] return completion diff --git a/Lib/test/test_pyrepl/test_pyrepl.py b/Lib/test/test_pyrepl/test_pyrepl.py index c11c759f559aff..7518e253bca4d2 100644 --- a/Lib/test/test_pyrepl/test_pyrepl.py +++ b/Lib/test/test_pyrepl/test_pyrepl.py @@ -1270,6 +1270,39 @@ def test_completions(self): output = reader.readline() self.assertEqual(output, expected) + @patch("pkgutil.iter_modules", lambda: [ModuleInfo(None, "apkg", True)]) + @patch( + "_pyrepl._module_completer.ModuleCompleter.iter_submodules", + lambda *_: [ + ModuleInfo(None, "foofoo", False), + ModuleInfo(None, "bar", False), + ModuleInfo(None, "barbar", False), + ], + ) + def test_import_completions_with_spaces(self): + cases = ( + ("import ap\t\n", "import apkg"), + ("import apkg .f\t\n", "import apkg .foofoo"), + ("import apkg. f\t\n", "import apkg. foofoo"), + ("import apkg . f\t\n", "import apkg . foofoo"), + ("import apkg .b\t\n", "import apkg .bar"), + ("import apkg. b\t\n", "import apkg. bar"), + ("import apkg . b\t\n", "import apkg . bar"), + ("import apkg .barb\t\n", "import apkg .barbar"), + ("import apkg. barb\t\n", "import apkg. barbar"), + ("import apkg .bar .f\t\n", "import apkg .bar .foofoo"), + ("import apkg .bar. f\t\n", "import apkg .bar. foofoo"), + ("import apkg .bar .b\t\n", "import apkg .bar .bar"), + ("import apkg .bar. b\t\n", "import apkg .bar. bar"), + ("import apkg . bar . barb\t\n", "import apkg . bar . barbar"), + ) + for code, expected in cases: + with self.subTest(code=code): + events = code_to_events(code) + reader = self.prepare_reader(events, namespace={}) + output = reader.readline() + self.assertEqual(output, expected) + @patch("pkgutil.iter_modules", lambda: [ModuleInfo(None, "public", True), ModuleInfo(None, "_private", True)]) @patch("sys.builtin_module_names", ()) diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-29-16-22-42.gh-issue-69605.PvQa2m.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-29-16-22-42.gh-issue-69605.PvQa2m.rst new file mode 100644 index 00000000000000..d290a0c91eab11 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-29-16-22-42.gh-issue-69605.PvQa2m.rst @@ -0,0 +1,2 @@ +Fix :term:`REPL` completions inserted incorrectly in some edge cases +when there was spaces in import statements.