Nick Coghlan <ncogh...@gmail.com> added the comment:
The relevant functions: * PyRun_InteractiveLoopFlags: https://github.com/python/cpython/blob/e8113f51a8bdf33188ee30a1c038a298329e7bfa/Python/pythonrun.c#L89 * PyRun_InteractiveOneObjectEx: https://github.com/python/cpython/blob/e8113f51a8bdf33188ee30a1c038a298329e7bfa/Python/pythonrun.c#L180 So it turns out I was wrong: nothing is getting cleared anywhere, but instead each statement in the REPL is *importing* `__main__` again in order to find the namespace to use for the statement execution. Because of the specific API it uses to do that, a non-module object like the one I injected gets replaced with a regular (empty) module object: https://github.com/python/cpython/blob/027b09c5a13aac9e14a3b43bb385298d549c3833/Python/import.c#L791 However, it *doesn't* have the extra code needed to make the `builtins` available: https://github.com/python/cpython/blob/027b09c5a13aac9e14a3b43bb385298d549c3833/Python/import.c#L932 So I now think the only actual *bug* here is the fact that the REPL isn't making sure that `__builtins__` is set appropriately - the rest can be chalked up to implementation defined behaviour around what happens if `__main__` gets replaced or removed in sys.modules while the REPL is running. ---------- _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue36665> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com