Olical / conjure

Interactive evaluation for Neovim (Clojure, Fennel, Janet, Racket, Hy, MIT Scheme, Guile, Python and more!)

Home Page:https://conjure.fun

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Swap `__name__` to something other than `__main__` in Python REPLs

Olical opened this issue · comments

As a few people have been discussing on Discord, the Python REPL leaves __name__ bound to the default __main__ which means your __main__ block is run when you load a buffer into the REPL. This is pretty unintuitive and probably dangerous.

We should bind __name__ to __repl__ or maybe even the name of the Python module you're currently editing if that can always be cleanly inferred. Looking at what other tooling does here may also be helpful especially if people already have expectations about how this should work from other tools.

Would deleting the __name__ variable be a reasonable thing to do so that the REPL environment does think that it's running a program or script when it starts up?

$ python
Python 3.11.6 | packaged by conda-forge | (main, Oct  3 2023, 10:40:37) [Clang 15.0.7 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> __name__
'__main__'
>>> del __name__
>>> __name__
'builtins'
>>> print(__name__)
builtins
>>> del __name__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__name__' is not defined
>>> __name__ == '__main__'
False

In part 6, Modules, in the Python Tutorial it says:

To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).

Rather than deleting (just in case someone is assuming that it'll exist and be a string) I've set __name__ = '__repl__' on setup. Hopefully this should fix things and be intuitive. This is on the develop branch, please let me know if this works in your use cases!

That should provide less surprise. Thanks!