None IPython-beyond-plain-Python-Fernando-Perez

IPython: an environment for interactive computing

Based on Introduction to IPYthon Notebook by Fernando Perez.

  • Minor modifications, Sep 2013 (Hans Fangohr)
  • Update to Python 3, September 2016 (Hans Fangohr)
  • Reviewed Jan 2022 (Hans Fangohr)

What is IPython?

  • Short for Interactive Python
  • A platform for you to interact with your code and data
  • The notebook: a system for literate computing
    • The combination of narrative, code and results
    • Weave your scientific narratives together with your computational process
  • Tools for easy parallel computing
    • Interact with many processes

IPython at the terminal

The basic IPython client: at the terminal, simply type ipython:

$ ipython
Python 3.5.1 |Anaconda 4.0.0 (x86_64)| (default, Dec  7 2015, 11:24:55) 
Type "copyright", "credits" or "license" for more information.

IPython 4.1.2 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: 

Some other tutorial help/resources :

IPython: beyond plain Python

When executing code in IPython, all valid Python syntax works as-is, but IPython provides a number of features designed to make the interactive experience more fluid and efficient.

First things first: running code, getting help

In the notebook, to run a cell of code, hit Shift-Enter. This executes the cell and puts the cursor in the next cell below, or makes a new one if you are at the end. Alternately, you can use:

  • Alt-Enter to force the creation of a new cell unconditionally (useful when inserting new content in the middle of an existing notebook).
  • Control-Enter executes the cell and keeps the cursor in the same cell, useful for quick experimentation of snippets that you don't need to keep permanently.
In [1]:
print("Hello")
Hello

Getting help

In [2]:
?

Help with ?

Typing object_name? will print all sorts of details about any object, including docstrings, function definition lines (for call arguments) and constructor details for classes.

In [3]:
import scipy.optimize
scipy.optimize.bisect?
In [4]:
scipy.optimize?
In [5]:
*int*?

An IPython quick reference card:

In [6]:
%quickref

Tab completion

Tab completion, especially for attributes, is a convenient way to explore the structure of any object you’re dealing with. Simply type object_name.<TAB> to view the object’s attributes. Besides Python objects and keywords, tab completion also works on file and directory names.

In [7]:
import math
In [ ]:
math.

The interactive workflow: input, output, history

In [9]:
2 + 10
Out[9]:
12
In [10]:
_ + 10
Out[10]:
22

Output control

You can suppress the storage and rendering of output if you append ; to the last cell (this comes in handy when plotting with matplotlib, for example):

In [11]:
10 + 20;
In [12]:
_
Out[12]:
22

Output history

The output is stored in _N and Out[N] variables:

In [13]:
Out[9]
Out[13]:
12
In [14]:
_9
Out[14]:
12

And the last three have shorthands for convenience:

In [15]:
print('last output:', _)
print('next one   :', __)
print('and next   :', ___)
last output: 12
next one   : 12
and next   : 22

The input history is also available

In [16]:
In[11]
Out[16]:
'10 + 20;'
In [17]:
_i
Out[17]:
'In[11]'
In [18]:
_ii
Out[18]:
'In[11]'
In [19]:
print('last input:', _i)
print('next one  :', _ii)
print('and next  :', _iii)
last input: _ii
next one  : _i
and next  : In[11]

Accessing the underlying operating system

Note: the commands below work on Linux or Macs, but may behave differently on Windows, as the underlying OS is different. IPython's ability to access the OS is still the same, it's just the syntax that varies per OS.

In [20]:
!pwd
/Users/py4cs/git/teaching-python/notebook
In [21]:
files = !ls
print("My current directory's files:")
print(files)
My current directory's files:
['17-pandas.ipynb', 'IPython-beyond-plain-Python-Fernando-Perez.html', 'IPython-beyond-plain-Python-Fernando-Perez.ipynb', 'IPythonNotebookIntroduction.html', 'IPythonNotebookIntroduction.ipynb', 'Makefile', 'Matplotlib.html', 'Matplotlib.ipynb', 'Testing-intro.html', 'Testing-intro.ipynb', '__pycache__', 'filename.pdf', 'filename.png', 'inverse-function-through-rootfinding.ipynb', 'lab1.ipynb', 'lab1.pdf', 'lab2.ipynb', 'lab3.ipynb', 'lab4.ipynb', 'lab5.ipynb', 'lab6.ipynb', 'lab7.ipynb', 'lab8.ipynb', 'mod.py', 'pandas-intro.html', 'same-or-differents-object.ipynb', 'speed-map-vs-for-loop.ipynb', 'test.svg', 'update-web.sh']

Beyond Python: magic functions

The IPython 'magic' functions are a set of commands, invoked by prepending one or two % signs to their name, that live in a namespace separate from your normal Python variables and provide a more command-like interface. They take flags with -- and arguments without quotes, parentheses or commas. The motivation behind this system is two-fold:

  • To provide an orthogonal namespace for controlling IPython itself and exposing other system-oriented functionality.

  • To expose a calling mode that requires minimal verbosity and typing while working interactively. Thus the inspiration taken from the classic Unix shell style for commands.

In [23]:
%magic

Line vs cell magics:

In [24]:
%timeit range(10)
103 ns ± 1.96 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In [25]:
%%timeit
range(10)
range(100)
214 ns ± 1.09 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Line magics can be used even inside code blocks:

In [26]:
for i in range(5):
    size = i*100
    print('size:',size)
    %timeit range(size)
size: 0
74 ns ± 4.59 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
size: 100
108 ns ± 1.47 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
size: 200
112 ns ± 1.83 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
size: 300
133 ns ± 1.02 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
size: 400
133 ns ± 1.9 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Magics can do anything they want with their input, so it doesn't have to be valid Python:

In [27]:
%%bash
echo "My shell is:" $SHELL
echo "My system uptime is:"
uptime
My shell is: /bin/zsh
My system uptime is:
17:01  up 11 days, 57 mins, 5 users, load averages: 2.62 5.14 5.06

Another interesting cell magic: create any file you want locally from the notebook:

In [28]:
%%file test.txt
This is a test file!
It can contain anything I want...

more...
Writing test.txt
In [29]:
!cat test.txt
This is a test file!
It can contain anything I want...

more...

Let's see what other magics are currently defined in the system:

In [30]:
%lsmagic
Out[30]:
Available line magics:
%alias  %alias_magic  %autoawait  %autocall  %automagic  %autosave  %bookmark  %cat  %cd  %clear  %colors  %conda  %config  %connect_info  %cp  %debug  %dhist  %dirs  %doctest_mode  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %lf  %lk  %ll  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %lx  %macro  %magic  %man  %matplotlib  %mkdir  %more  %mv  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %pip  %popd  %pprint  %precision  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %rep  %rerun  %reset  %reset_selective  %rm  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode

Available cell magics:
%%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile

Automagic is ON, % prefix IS NOT needed for line magics.

Running normal Python code: execution and errors

Not only can you input normal Python code, you can even paste straight from a Python or IPython shell session:

In [31]:
>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
...     print(b)
...     a, b = b, a+b
1
1
2
3
5
8
In [32]:
In [1]: for i in range(10):
   ...:     print(i, end=' ')
   ...:     
0 1 2 3 4 5 6 7 8 9 

Error display

And when your code produces errors, you can control how they are displayed with the %xmode magic:

In [33]:
%%file mod.py

def f(x):
    return 1.0/(x-1)

def g(y):
    return f(y+1)
Overwriting mod.py

Now let's call the function g with an argument that would produce an error:

In [34]:
import mod
mod.g(0)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
/var/folders/15/ycjq13rn4ql_v3dwptl123th0000gs/T/ipykernel_36841/434918578.py in <module>
      1 import mod
----> 2 mod.g(0)

~/git/teaching-python/notebook/mod.py in g(y)
      4 
      5 def g(y):
----> 6     return f(y+1)

~/git/teaching-python/notebook/mod.py in f(x)
      1 
      2 def f(x):
----> 3     return 1.0/(x-1)
      4 
      5 def g(y):

ZeroDivisionError: float division by zero

Verbose exceptions

In [36]:
%xmode verbose
mod.g(0)
Exception reporting mode: Verbose
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
/var/folders/15/ycjq13rn4ql_v3dwptl123th0000gs/T/ipykernel_36841/2816820657.py in <module>
      1 get_ipython().run_line_magic('xmode', 'verbose')
----> 2 mod.g(0)
        global mod.g = <function g at 0x7fd3b53c8f70>

~/git/teaching-python/notebook/mod.py in g(y=0)
      4 
      5 def g(y):
----> 6     return f(y+1)
        global f = <function f at 0x7fd3b53c8dc0>
        y = 0

~/git/teaching-python/notebook/mod.py in f(x=1)
      1 
      2 def f(x):
----> 3     return 1.0/(x-1)
        x = 1
      4 
      5 def g(y):

ZeroDivisionError: float division by zero

The default %xmode is "context", which shows additional context but not all local variables. Let's restore that one for the rest of our session. (Another option is %xmode plain providing even less detail.)

In [37]:
%xmode context
Exception reporting mode: Context

Raw Input in the notebook

Since 1.0 the IPython notebook web application support raw_input which for example allow us to invoke the %debug magic in the notebook:

In [38]:
mod.g(0)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
/var/folders/15/ycjq13rn4ql_v3dwptl123th0000gs/T/ipykernel_36841/4151852588.py in <module>
----> 1 mod.g(0)

~/git/teaching-python/notebook/mod.py in g(y)
      4 
      5 def g(y):
----> 6     return f(y+1)

~/git/teaching-python/notebook/mod.py in f(x)
      1 
      2 def f(x):
----> 3     return 1.0/(x-1)
      4 
      5 def g(y):

ZeroDivisionError: float division by zero
In [39]:
%debug
> /Users/py4cs/git/teaching-python/notebook/mod.py(3)f()
      1 
      2 def f(x):
----> 3     return 1.0/(x-1)
      4 
      5 def g(y):

ipdb> exit

Don't forget to exit your debugging session. Raw input can of course be use to ask for user input:

Plotting in the notebook

This imports numpy as np and matplotlib's plotting routines as plt, plus setting lots of other stuff for you to work interactivel very easily:

In [40]:
%matplotlib inline
In [41]:
import numpy as np
import matplotlib.pyplot as plt

## Show plots inside the notebook as svg
%config InlineBackend.figure_formats = ['svg'] 
In [42]:
fig, ax = plt.subplots()
x = np.linspace(0, 2*np.pi, 300)
y = np.sin(x**2)
plt.plot(x, y)
plt.title("A little chirp")
Out[42]:
Text(0.5, 1.0, 'A little chirp')
2022-01-17T17:03:18.513562 image/svg+xml Matplotlib v3.4.3, https://matplotlib.org/

The IPython kernel/client model

We can also run an IPYthon notebook on a server, and connect to that notebook session remotely or from the local machine. This magic gives us some details:

In [43]:
%connect_info
{
  "shell_port": 51751,
  "iopub_port": 51752,
  "stdin_port": 51753,
  "control_port": 51755,
  "hb_port": 51754,
  "ip": "127.0.0.1",
  "key": "aeb61d19-0af0aa2eea25e567a5db0ca9",
  "transport": "tcp",
  "signature_scheme": "hmac-sha256",
  "kernel_name": ""
}

Paste the above JSON into a file, and connect with:
    $> jupyter <app> --existing <file>
or, if you are local, you can connect with just:
    $> jupyter <app> --existing kernel-435bb674-37dc-456b-8161-8e01861aa4e4.json
or even just:
    $> jupyter <app> --existing
if this is the most recent Jupyter kernel you have started.

So for example we can open a text-based ipython console connected to this session using:

!jupyter console --existing

Or open a QTConsole from here using

In [ ]:
%qtconsole

Play audio, use widgets and Binder

Further reading

The Jupyter Notebook has become a central tool for interactive data exploration and data analysis. I would agree that most data scientists will see the Jupyter notebook as the default place to start a data exploration, analysis and machine learning project.

Why is this so? The combination of annotation, code snippets, inlined results from computation or visualisation and the automatic logging of these steps in a notebook file can be of great use for research and development activities. A slightly longer summary is available here.

Some recent publications on the topic: