In this second article of the series on Python we're going to cover some really great features of the interactive interpreter. We'll see that a full-fledged debugger may not even be necessary to get serious work done in Python.
Python (usually) comes with an interactive interpreter that supports executing your code one line after another -- just like the shell does. This Read-Eval-Print-Loop (REPL) evaluates your input as soon as you press ENTER.
Consider a short example how this might look like after firing up the the interpreter python3 on the shell:
We can also import an existing module - this is where it gets really interesting for prototyping and debugging. Consider the following script:
Let's now import that module from the interactive interpreter and call foo() on it:
What if we now change some part of the original source file and call foo() again?
As we can see, the module contents are not reloaded automatically. So let's fix that by using importlib:
Isn't that great? We can develop a module in a step-by-step manner, being able to test its behavior from the interpreter immediately. This works best if we keep functions and classes decoupled from each other inside modules. As a side effect, this might even lead to improved designs.
Another neat feature: readline vi mode is supported. Let's try this by putting the following into your ~/.inputrc:
Now the Python interpreter prompt shows a + sign at the beginning of each line to signalize insert mode. It will change to : in normal mode:
Conclusion
The interactive interpreter seems to be a great tool for debugging and prototyping. What else do you think would be interesting to talk about? Just contact me on twitter: @ronalterde.