emacs-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Python REPL using standard library functions


From: Yuri Khan
Subject: Re: Python REPL using standard library functions
Date: Mon, 2 Nov 2020 18:40:14 +0700

On Mon, 2 Nov 2020 at 16:50, Dmitry Gutov <dgutov@yandex.ru> wrote:
>
> On 02.11.2020 08:14, Yuri Khan wrote:
> > Python has ast.parse(), compile() and exec(), all three exposed in the
> > standard library.
>
> I'd be willing to bet that any given Python REPL doesn't use them, though.

One of the guiding principles of Python is “There must be one — and
preferably only one — obvious way to do it”. Implementing a REPL in
terms of ast.parse, compile() and exec is one obvious way to do it.
There is a catch that compile() with an option argument can be used
instead of ast.parse, so that’s another obvious way to do it. Both are
fully exposed to the user though.

Indeed, my limited experimentation shows I can augment these built-in
functions and they are immediately picked up by at least one REPL:

$ ipython3
In [1]: import ast
In [2]: old_ast_parse = ast.parse
In [3]: def my_parse(*args, **kwargs):
   ...:     print('in ast.parse')
   ...:     return old_ast_parse(*args, **kwargs)
   ...:
In [4]: ast.parse = my_parse
In [5]: 2+2
Out[5]: 4

# no effect so far

In [7]: old_compile = __builtins__.compile
In [8]: def my_compile(*args, **kwargs):
   ...:     print('in compile')
   ...:     return old_compile(*args, **kwargs)
   ...:
In [9]: __builtins__.compile = my_compile
In [10]: 2+2
in compile
in compile
in compile
in compile
in compile
in compile
Out[10]: 4

# now we are getting something,
# not sure why so many calls

In [11]: old_exec = __builtins__.exec
in compile
in compile
in compile
in compile
in compile
in compile
In [12]: def my_exec(*args, **kwargs):
    ...:     print('in exec')
    ...:     return old_exec(*args, **kwargs)
    ...:
in compile
in compile
in compile
in compile
in compile
in compile
In [13]: __builtins__.exec = my_exec
in compile
in compile
in compile
in compile
in compile
in compile
In [14]: 2+2
in compile
in compile
in compile
in compile
in compile
in compile
in exec
Out[14]: 4



reply via email to

[Prev in Thread] Current Thread [Next in Thread]