Among the IPython examples is one showing how to implement a progress bar.
I, however, think the implementation used in the example has some severe
limitations which are not mentioned. Everything displayed in an IPython notebook
will be saved in the notebook. It seem that
the notebook and adds an invisible
<div> to the notebook.
Luckily, IPython 2.0 introduced widgets allowing it to implement a progress bar without that flaw. First we need a Python class for our widget:
DOMWidget is the base class we have to use for any widget that is intended
to be displayed in the notebook. In the widget class we define a number of class
variables which will become attributes the widget. Each of those is an instance
of a traitlet, a type-safe property. The
sync keyword argument tells the
traitlet to automatically synchronize with the front-end code which we will
traitlet. The basic structure looks like this:
All of the code has to be wrapped in the
require call. In IPython 3
(currently in development) the
manager will be passed to the
function with the front-end code. However, in IPython 2 this in not the case.
Therefore, we check first whether the values have been passed and otherwise use
the IPython 2 method for access. This ensures the code will work with the
current and upcoming version of IPython. After that we extend the
DOMWidgetView class and add our front-end code. The final step is to
register the derived class with the
WidgetManager so that it gets connected
to the back-end.
Now, let us fill in the actual front-end code. First we need a
function which adds the required HTML elements and sets a CSS property on the
The updates to the progress bar are performed by the
First we set the
width property of the containing element again because
IPython might override after the first call to
render. Then we read out the
progress from the model (our Python widget class) and set the width of the
inner div accordingly.
in the IPython notebook, then instantiate and display the
By setting the
progress attribute of the instance the progress bar will be
automatically updated. Moreover, you can do it as many times as you like without
blowing up the notebook’s size.