hy icon indicating copy to clipboard operation
hy copied to clipboard

Make repl embeddable

Open gilch opened this issue 7 years ago • 2 comments

Look what IPython can do:

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> foo = 42
>>> import IPython; IPython.embed()
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 6.1.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: foo
Out[1]: 42

In [2]: bar = True

In [3]: exit

>>> foo
42
>>> bar
True
>>>

Let's try that in Hy.

(hy36env) C:\Users\ME\workspace\hy36env\Scripts>python
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> foo = 42
>>> from hy.cmdline import run_repl
>>> run_repl()
hy 0.13.0+15.g2e465db using CPython(v3.6.1:69c0db5) 3.6.1 on Windows
=> foo
Traceback (most recent call last):
  File "c:\users\me\documents\github\hy\hy\importer.py", line 198, in hy_eval
    return eval(ast_compile(expr, "<eval>", "eval"), namespace)
  File "<eval>", line 1, in <module>
NameError: name 'foo' is not defined
=> (exit)

(hy36env) C:\Users\ME\workspace\hy36env\Scripts>

We can launch the repl from Python. However, we lost our vars, and (exit) kicks us all the way back to the system shell. Could Hy's repl be made embeddable like IPython?

gilch avatar Jul 14 '17 20:07 gilch

This would be nice to have for debugging.

Kodiologist avatar Jul 14 '17 20:07 Kodiologist

Python also has an embeddable repl in the standard library, and not just the debugger. It's in the code module. The easiest way to start it up is with code.interact(). You can also pass in the starting locals. Hy ought to have something like it.

gilch avatar May 27 '18 23:05 gilch

This works now, but it should probably be more prominently advertised in the documentation:

Python 3.10.6 (main, Nov  2 2022, 18:53:38) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> foo = 42
>>> import hy.cmdline; hy.cmdline.HyREPL(locals = locals()).run()
Hy 0.25.0 using CPython(main) 3.10.6 on Linux
=> (+ foo 1)
43
=> 
now exiting HyREPL...
0
=> foo + 2
44
=>

Two issues I notice are that sys.ps1 isn't restored to its old value once the Hy REPL terminates, and my Hy REPL history (like, even from before this session) got leaked into my Python REPL history.

Kodiologist avatar Nov 10 '22 20:11 Kodiologist