Retracing your steps in an interactive python env
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Mon Sep 14 20:09:29 EDT 2009
On Mon, 14 Sep 2009 14:52:34 -0500, Jack Norton wrote:
> it would be really nice to be
> able to _ask_ python what makes up a def. Something like this (remember
> I am using IPython interactive interpreter session):
> In [0]: def func(input):
> .........:>>>print "im in this function!" + str(input)
> .........:>>>print "doing some stuff" .........:>>>sleep(10)
>
> Then later on while still in this interactive shell session I could do
> something like:
> In [1]: what_is_in(func)
> "The def for func(input) is:"
> print "im in this function!" + str(input) print "doing some stuff"
> sleep(10)
>
> and therefore be able to recount what I just did.
Can't be done in the CPython interactive interpreter, because code is
compiled before being executed. It doesn't save the source code when it
compiles the function definition, so there's no way it can show you the
source code. That's why interactive tracebacks don't show you the
offending line that failed (with the exception of syntax errors) unless
you have imported the function from a .py file.
You could probably mess about with the readline library to save a copy of
everything to a history file.
Another alternative is to disassemble the compiled function, and try to
determine what it does from that. See the dis module.
I wonder whether there's a third party module which will take the output
of dis.dis and try to reverse engineer Python code from it?
--
Steven
More information about the Python-list
mailing list