gh-127960 Fix the REPL to set the correct namespace by setting the correct __main__ module (gh-134275)

The `__main__` module imported in the `_pyrepl` module points to the `_pyrepl` module itself when the interpreter was launched without `-m` option and didn't execute a module,
while it's an unexpected behavior that `__main__` can be `_pyrepl` and relative imports such as `from . import *` works based on the `_pyrepl` module.

Co-authored-by: Łukasz Langa <lukasz@langa.pl>
This commit is contained in:
Yuichiro Tachibana (Tsuchiya) 2025-05-21 19:18:00 -05:00 committed by GitHub
parent a66bae8bb5
commit b1b8962443
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 85 additions and 34 deletions

View file

@ -1,6 +1,7 @@
import errno
import os
import sys
import types
CAN_USE_PYREPL: bool
@ -29,12 +30,10 @@ def interactive_console(mainmodule=None, quiet=False, pythonstartup=False):
print(FAIL_REASON, file=sys.stderr)
return sys._baserepl()
if mainmodule:
namespace = mainmodule.__dict__
else:
import __main__
namespace = __main__.__dict__
namespace.pop("__pyrepl_interactive_console", None)
if not mainmodule:
mainmodule = types.ModuleType("__main__")
namespace = mainmodule.__dict__
# sys._baserepl() above does this internally, we do it here
startup_path = os.getenv("PYTHONSTARTUP")