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:

>>> for i in range(5):
...  print(i)
...
0
1
2
3
4
>>>

We can also import an existing module - this is where it gets really interesting for prototyping and debugging. Consider the following script:

""" demo.py """
def foo():
    print('foo')

Let's now import that module from the interactive interpreter and call foo() on it:

>>> import demo
>>> demo.foo()
foo
>>>

What if we now change some part of the original source file and call foo() again?

""" demo.py """
def foo():
    print('bar')
>>> demo.foo()
foo
>>>

As we can see, the module contents are not reloaded automatically. So let's fix that by using importlib:

>>> import importlib
>>> importlib.reload(demo)
>>> demo.foo()
bar
>>>

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:

set editing-mode vi
set keymap vi
set show-mode-in-prompt on

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:

$ python3
+>>> 
:>>>

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.