Skip to content

Add dask.widgets and migrate HTML reprs to jinja2 - #8019

Merged
jacobtomlinson merged 16 commits into
dask:mainfrom
jacobtomlinson:widgets
Aug 18, 2021
Merged

jacobtomlinson merged 16 commits into
dask:mainfrom
jacobtomlinson:widgets

Conversation

@jacobtomlinson

@jacobtomlinson jacobtomlinson commented Aug 11, 2021 •

Copy link
Copy Markdown
Member

This PR extends dask/distributed#5188. This goal of this PR is to make HTML reprs more maintainable by using jinja2 templates instead of storing HTML in multiline strings. It also aims to make it easy for downstream projects to make use of and extend this tooling.

Changes

  • Upstreams distributed.widgets (I will PR to distributed separately to use this instead).
  • Make jinja2 a required dependency.
  • Makes the widgets more extensible with TEMPLATE_PATHS and FILTERS constants which other packages can make use of.
  • Add tests for dask.widgets.
  • Migrate Array, Dataframe, HighLevelGraph and Layer to use widget templates.
  • Upstream distributed.utils.typename to dask.utils.typename as it was useful in those migrations.

Writing HTML reprs

To add a new HTML repr you can import dask.widgets.get_template which can be used to load jinja2 templates from dask/widgets/templates.

from dask.widgets import get_template

class MyClass():
    ...

    def _repr_html_(self):
        return get_template("my_template.html.j2").render(**kwargs)
<!-- dask/widgets/templates/my_template.html.j2 -->
<div>
    Render values.
    {{ some_kwarg }}
</div>

Jinja2 also supports filters which are functions that can be used via a | pipe within the template. The dask.widgets module adds a bunch of utilities from dask.utils to the default filters.

<div>
    {{ nbytes | format_bytes }} <!-- this is the format_bytes from dask.utils -->
</div>

For downstream projects

Downstream projects can register their own templates directories and filters, similar to how they can extend the Dask config system.

Example

# my_package/__init__.py
from dask.widgets import TEMPLATE_PATHS, FILTERS


def my_awesome_util(info):
    # Do something to info
    return info

TEMPLATE_PATHS.append("my_package/widgets/templates")  # probably use some fancy os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates")
FILTERS["my_awesome_util"] = my_awesome_util

Within that project they can use the widgets tooling to access their own templates and use their own filters.

from dask.widgets import get_template

class MyAwesomeClass():
    ...

    def _repr_html_(self):
        return get_template("my_awesome_template.html.j2").render(**kwargs)

Then in my_awesome_template.html.j2 in their custom templates directory.

<!-- my_package/widgets/templates/my_awesome_template.html.j2 -->
<div>
    Render values and run your own filters on them.
    {{ some_kwarg | my_awesome_util }}
</div>

The MANIFEST.in file probably will need updating in the subproject to ensure that *.j2 files are packaged.

@jsignell

Copy link
Copy Markdown
Member

Just a note that this will be very good content to include in the dask developer guide, once we have the organization sorted :)

@jsignell jsignell left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This all looks great, but I don't think jinja2 should be a required dependency of dask (similar to how ipywidgets isn't a dependency). All of these display methods are only used in notebooks and notebooks already depend on jinja2, so I think it's just a matter of adding a skip if ImportError to the widgets module.

@jacobtomlinson

jacobtomlinson commented Aug 12, 2021 •

Copy link
Copy Markdown
Member Author

Just a note that this will be very good content to include in the dask developer guide, once we have the organization sorted :)

Absolutely! I thought about adding a docs page now, but wasn't sure where to put it. So decided to put it in the PR description for now.

All of these display methods are only used in notebooks

I can see this being applicable in more places than notebooks. The dashboard in distributed and performance reports are prime candidates. Maybe it should be added to the diagnostics extras require instead?

My brain isn't working and I'm struggling to work out how to do the skip ImportError, @jsignell can you link to an example of where this has been done somewhere else?

@jsignell

Copy link
Copy Markdown
Member

I can see this being applicable in more places than notebooks. The dashboard in distributed and performance reports are prime candidates. Maybe it should be added to the diagnostics extras require instead?

Oh! I missed that this is also affecting the dashboard. In that case, yeah I think it belongs wherever bokeh is.

My brain isn't working and I'm struggling to work out how to do the skip ImportError, @jsignell can you link to an example of where this has been done somewhere else?

dataframe is a good example with a clear error message: https://github.com/dask/dask/blob/main/dask/dataframe/__init__.py

@jacobtomlinson

Copy link
Copy Markdown
Member Author

Awesome thanks @jsignell. I've updated that. Not 100% sure if I've done the right thing in the CI.

@jacobtomlinson

Copy link
Copy Markdown
Member Author

Hrm no that's not going to work, anywhere we import the widgets utils (like array or distributed) will now raise that import error. Do you think I should move the from dask.widgets import get_template inside the _repr_html_ methods?

@jsignell

jsignell commented Aug 12, 2021 •

Copy link
Copy Markdown
Member

Do you think I should move the from dask.widgets import get_template inside the _repr_html_ methods?

Yeah that's one approach, or the widgets module could not trigger the warning and instead the warning could be triggered from within the _repr_html_ methods.

Like you could move the try/except ImportError to the __init__.py. Something like this:

try:
    from .widgets import FILTERS, TEMPLATE_PATHS, get_environment, get_template

except ImportError as e:
    msg = (
        "Dask diagnostics requirements are not installed.\n\n"
        "Please either conda or pip install as follows:\n\n"
        "  conda install dask                     # either conda install\n"
        '  python -m pip install "dask[diagnostics]" --upgrade  # or python -m pip install'
    )
    FILTERS = dict()
    TEMPLATE_PATHS = []

    def get_environment(*args, **kwargs):
        raise ImportError(msg) from e

    def get_template(*args, **kwargs):
        raise ImportError(msg) from e

@jacobtomlinson

Copy link
Copy Markdown
Member Author

Oooh I like that!

@jsignell

Copy link
Copy Markdown
Member

This looks good to me! I'll let @jrbourbeau give a final 👍

Comment thread dask/utils.py Outdated
Comment on lines +1816 to +1834
def typename(typ, short=False):
"""Return name of type

Examples
--------
>>> from distributed import Scheduler
>>> typename(Scheduler)
'distributed.scheduler.Scheduler'
>>> typename(Scheduler, short=True)
'distributed.Scheduler'
"""
try:
if short:
module, *_ = typ.__module__.split(".")
else:
module = typ.__module__
return module + "." + typ.__name__
except AttributeError:
return str(typ)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's already a typename function in this module. Can we use that instead? It looks like we might be able to use the other typename as-is. It doesn't have the short= keyword, but IIUC we're not using that anywhere anyways

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh interesting I hadn't spotted that! I just upstreamed the one from distributed. I've merged them now.

I added short= myself because I found a few places where this functionality was duplicated and used the short version. So this helps reduce some code duplication in other places.

Comment thread dask/widgets/__init__.py Outdated
" conda install dask # either conda install\n"
' python -m pip install "dask[diagnostics]" --upgrade # or python -m pip install'
)
exception = e

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick: I'm not sure why this is needed. Is except ImportError as exception: a few lines above equivalent?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems that the e gets dereferenced outside the try block despite it being used within the method.

MCRE

try:
    raise Exception()
except Exception as e:
    def foo():
        raise Exception() from e

foo()
Traceback (most recent call last):
  File "/tmp/test.py", line 7, in <module>
    foo()
  File "/tmp/test.py", line 5, in foo
    raise Exception() from e
NameError: name 'e' is not defined

So you need to assign it to a variable explicitly to maintain the reference.

try:
    raise Exception()
except Exception as e:
    exception = e  # Make a reference here
    def foo():
        raise Exception() from exception

foo()
Traceback (most recent call last):
  File "/tmp/test.py", line 2, in <module>
    raise Exception()
Exception

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/tmp/test.py", line 8, in <module>
    foo()
  File "/tmp/test.py", line 6, in foo
    raise Exception() from exception
Exception

@jacobtomlinson

Copy link
Copy Markdown
Member Author

I am planning on merging this in 24 hours if there is no further feedback.

cc @jsignell @jrbourbeau

@jacobtomlinson

Copy link
Copy Markdown
Member Author

Merging

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants