python / cpython

The Python programming language
https://www.python.org/
Other
60.77k stars 29.34k forks source link

New REPL does not include globals from executed module when used with `-i` #120678

Open AlexWaygood opened 1 week ago

AlexWaygood commented 1 week ago

Bug report

Bug description:

If I have a module called foo.py with the following contents in the root of my CPython local clone:

class Foo: pass

Then running PYTHON_BASIC_REPL=1 ./python.exe -i foo.py, I get the following behaviour: foo.py is executed, and the Foo class is available in the globals of the REPL:

~/dev/cpython (main)⚡ % PYTHON_BASIC_REPL=1 ./python.exe -i foo.py 
>>> Foo
<class '__main__.Foo'>

But with the new REPL, the Foo class isn't available!

~/dev/cpython (main)⚡ % ./python.exe -i foo.py 
>>> Foo
Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
    Foo
NameError: name 'Foo' is not defined
>>> 

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Linked PRs

eryksun commented 1 week ago

It seems the new REPL doesn't get executed in the __main__ namespace. This can be worked around manually:

$ python -ic "class Foo: pass"
>>> Foo
Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
    Foo
NameError: name 'Foo' is not defined
>>> import sys
>>> from _pyrepl.simple_interact import run_multiline_interactive_console
>>> run_multiline_interactive_console(sys.modules['__main__'])
>>> Foo
<class '__main__.Foo'>
>>> dir()
['CAN_USE_PYREPL', 'Foo', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'interactive_console', 'os', 'sys']

This can be addressed in "Lib/pyrepl/__main_\.py". All imports and assignments in that module (e.g. CAN_USE_PYREPL, interactive_console, os, and sys) should be uniquely prefixed to avoid collisions and to allow clearing them before calling run_interactive(mainmodule).

vstinner commented 1 week ago

I marked https://github.com/python/cpython/issues/120798 as a duplicate of this issue.

AlexWaygood commented 1 week ago

This is a regression that was caused by https://github.com/python/cpython/pull/119547.