2

I am trying to follow this example and this tutorial to make a D3 widget which displays D3 HTML code to a widget when a function is called. I was able to make it function within the notebook cells itself using %%javascript, but this would be messy for an end user to use.

How can I move the Python D3Widget class definition and Javascript D3View render code to external files so that the user can simply import the file and call the function?

I want the end result to look like this, where the user can simply import a function and call it.

1 Answer 1

1

Organize your code

In your notebook root folder create a package for your new widget. For example you can use the following directory structure:

helloworld/

    __init__.py
    helloworld_widget.py

    helloworldjs/
        helloworld.view.js

        css/
            helloworld.css

Program the server side

Inside helloworld/helloworld_widget.py, put your Python class:

from ipywidgets import widgets
from traitlets import Unicode

class HelloWorldWidget(widgets.DOMWidget):
    _view_module = Unicode("nbextensions/helloworld/helloworld_view", sync=True)
    _view_name = Unicode('HelloWorldView', sync=True)

That's it with your python code.

Create the Javascript view

In helloworld/helloworldjs/helloworld.view.js program your client side:

define(["nbextensions/widgets/widgets/js/widget"], function(widget) {

    var HelloWorldView = widget.DOMWidgetView.extend({

        render: function(){
            this.$el.text("Hello world");
        },
    });

    return {HelloWorldView: HelloWorldView}
});

Simple, isn't it? Last but not least...

Deploy the client side to the notebook's extensions folder

To do that you can program a function in your init.py and execute it inside your notebook every time your modify something in your Javascript view.

I use this one very similar to the following:

def notebook_install(overwrite=True, user=True):
    import os
    from notebook import install_nbextension
    from notebook.services.config import ConfigManager
    from IPython.display import display, Javascript

    js_path = os.path.join( os.path.dirname(__file__), 'helloworldjs')
    install_nbextension(js_path, overwrite=overwrite,
                        symlink=False, verbose=0, user=user)

Now you should be able to execute the following in your notebook:

from helloworld.helloworld_widget import HelloWorldWidget
hello = HellowWorldWidget()
hello

Enjoy!

Reading carefully this article should also help: https://carreau.gitbooks.io/jupyter-book/content/notebook-extensions.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.