4 ms·
I think there's a bit of a misunderstanding regarding exit. exit is not a keyword or a REPL command, it's actually a function exposed in the builtin package. yo
by mariocesar 2y ago
I think there's a bit of a misunderstanding regarding exit. exit is not a keyword or a REPL command, it's actually a function exposed in the builtin package. you can run "import builtins; builtins.exit()" and see that is there
To clarify, there are two things here: why exit exists in the REPL, and why it's a function. The exit() function is available only in the REPL, and it appears built-in, but it isn't part of the built-in namespace. Instead, exit is loaded automatically by the site module.
Heres is the code with the function site.main that is doing it: https://github.com/python/cpython/blob/8af84b503d0b62a3db0d806d39f42c1e08746079/Lib/site.py#L634-L661 https://github.com/python/cpython/blob/8af84b503d0b62a3db0d8... and more specifically here https://github.com/python/cpython/blob/8af84b503d0b62a3db0d806d39f42c1e08746079/Lib/site.py#L415 https://github.com/python/cpython/blob/8af84b503d0b62a3db0d8... on setquit
The line builtins.exit = _sitebuiltins.Quitter('exit', eof) shows that exit is set as a function. The Quitter class, which exit is an instance of, has a __call__ method, making it callable, so it as a function.
I don't believe you're wrong not understanding it; it's just that the process isn’t typically explained in detail, especially what happens when you start the REPL. This is why the message "Use exit() instead..." exists in the REPL, because of the need for clarification.
In a nutshell, exit is a function loaded into the built-ins by the site.py module, which automatically activates when the REPL starts. This automatic loading is what makes exit, help, __copyright__ and others available only in the interactive sessions.
- aeturnum 2y agoIt seems great to change the REPL to treat it like a statement! This is obviously a better user experience. I also think it's somewhat funny given Python's history on "should common functionality be accessed through statements or functions"[1]! [1] I hope it's obvious that special-casing exit in the REPL is a much more constrained special case than print being a keyword and the difference in scope makes all the difference in balancing accessibility and consistency.