# Writing an IPython extension to show object graphs¶

Idea: Reuse a Python package, pyrels, to display data structures graphically (see presentation at EuroPython 2008) in an IPython notebook.

Inspiration: Find an existing extension that already does something similar: display GraphViz DOT files. ipython-hierarchymagic does it!

In [1]:
%install_ext https://raw.github.com/tkf/ipython-hierarchymagic/master/hierarchymagic.py

Installed hierarchymagic.py. To use it, type:



This gives two new IPython magic commands: %hierarchy and %%dot, doing what you expect them to do, at least for %%dot. We skip %hierarchy here, but you can uncomment it to see the standard example.

In [2]:
# %hierarchy get_ipython()


This is actually the command that is pretty similar to what we want:

In [3]:
%%dot -f svg
digraph G {
a->b; b->c; c->d; c->a; d->b; d->a;
}


Now install pyrels 0.1.1 (or higher) if you don't have it already:

In [4]:
!pip install pyrels==0.1.1

Requirement already satisfied (use --upgrade to upgrade): pyrels==0.1.1 in /opt/lib/python2.7/site-packages
Cleaning up...



Now let's see if that worked as expected with a very simple example. Here we create some DOT code that we first display manually after passing it to the %%dot command:

In [5]:
from pyrels.pyrels2dot import namespace2dot_str
print namespace2dot_str({"myInt": 42})

digraph G {
overlap=false;

name4331282912 [label="myInt", shape="ellipse"];
int4298193560 [label="int: 42", shape="box"];

name4331282912 -> int4298193560 [label="ref"];

}


In [6]:
%%dot -f svg
digraph G {
overlap=false;

name4368865680 [label="myInt", shape="ellipse"];
int4298193560 [label="int: 42", shape="box"];

name4368865680 -> int4298193560 [label="ref"];

}


This is what we want to create directly with an extension using pyrels. The code to do that is on Gist.

In [7]:
# %install_ext file:///Users/dinu/Desktop/joy-of-scipy/ipython_objgraph_magic.py
%install_ext https://gist.github.com/deeplook/4731035/raw/daa82e13f6635f513694bffb0bb9bc8a1b4ceff2/ipython_object_graphs.py

Installed ipython_object_graphs.py. To use it, type:



Now we can create some data structure and display it (as a namespace) with the new magic command %%objgraph:

In [8]:
class C(object):
pass
n = 23
L = [1, 23, (2, 3), None, C]

In [9]:
%%objgraph -f svg
{"myInt": n, "myList": L}


Neat!

In []: