A blog about technical stuff


Jan Schulz

BI Engineer @ kfzteile24.de | Python enthusiast (knitpy, pandas, statsmodels, matplotlib, ggplot, pypandoc) | PhD student @ TU Freiberg (bibliometrics, academic research productivity, social networks, social capital) | Private homepage (de)

Github
Twitter
LinkedIn
Email

Archive | RSS

Demo mode for IPython (works in the notebook)

R has a demo mode, which lets you execute some demo of a function or a package. See e.g. demo(lm.glm) for such a thing.

An PR in IPython-extensions lets you do much the same:

It will get some demo code (which can be a function in a package or the matplotlib examples on github) and lets you execute that code by yourself. Specially formatted comments in the function will get turned into formatted text, if the frontend suppports it. It works in the notebook by adding new cells with the demo content or in the qtconsole/ipython directly by presetting it as new input (simple press enter) until the demo is over.

Writing a demo

Writing a demo is simple writing a function in a module. Markdown formatting in comments is possible and works in the notebook. In the qtconsole/IPython, they are simple comments. This is the demo example:

[...]

def demo_example():
    """An example how to write a demo."""
    # ## Comments
    # Comments are interpreted as markdown syntax, removing the 
    # initial `# `. If a comment starts only with `#`, it is interpreted 
    # as a code comment, which will end up together with the code.
    #change your name:
    name = "Jan"
    print("Hello {0}!".format(name))
    # ## Magics
    # Using magics would result in not compiling code, so magics 
    # have to be commented out. The demo will remove the comment
    # and insert it into the cell as code.
    #%%time
    _sum = 0
    for x in range(10000):
        _sum += x
    # Print the sum:
    print(_sum)

# This lets the `demo(ipyext.demo)` find only the `demo_example`. 
# Only modues with that variable will display an overview of 
# the available demos.
__demos__ = [demo_example]

Demo of demo mode :-)

Here are some videos of it in action:

IPython qtconsole

IPython demo mode in qtconsole

Jupyter Notebook (with IPython kernel)

IPython demo mode in jupyter notebook

If you have any comments, or know of examples for a package (needs to be plain python files available on github -> like for matplotlib), please leave it below or in the PR. Thanks!

comments powered by Disqus