[IPython-dev] [EXTERNAL] rant: "%matplotlib inline"

Shead, Timothy tshead at sandia.gov
Mon Jul 6 12:18:57 EDT 2015


> On Jul 6, 2015, at 9:35 AM, Matthias Bussonnier <bussonniermatthias at gmail.com> wrote:
> 
> 
>> On Jul 6, 2015, at 10:28, Shead, Timothy <tshead at sandia.gov> wrote:
>> 
>> At the risk of being self-serving, Toyplot (http://toyplot.readthedocs.org) is a plotting library for Python that Just Works when imported into a notebook.  The code to detect the notebook environment was trivial to write, and could easily be adapted to (ahem) legacy libraries.
> 
> I’m curious to know how you detect you are in a notebook in a reliable manner. 

Matthias:

The following code gets executed once when Toyplot is imported:

  def _ipython_register():
    try:
      import IPython
      if IPython.get_ipython():
        IPython.get_ipython().events.register("post_execute", _ipython_post_execute)
    except:
      pass

Thus, a callback gets executed every time a cell is run:

  def _ipython_post_execute():
    try:
      import IPython.display
      for canvas in [Canvas._autorender_list]:
        IPython.display.display(canvas)
    except:
      pass

… where the “Canvas” class has a _repr_html_(self) that returns the HTML representation of a figure, and Canvas._autorender_list is a list of Canvas objects to be rendered inline.  You could imagine adapting the _ipython_post_execute() callback to work with arbitrary objects, including libraries that are completely “IPython-unaware”.

Cheers,
Tim



More information about the IPython-dev mailing list