Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lazily load resource files #4297

Merged
merged 2 commits into from
Aug 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ Documentation

Internal Changes
~~~~~~~~~~~~~~~~
- Only load resource files when running inside a Jupyter Notebook
(:issue:`4294`) By `Guido Imperiale <https://github.com/crusaderky>`_


.. _whats-new.0.16.0:
Expand Down
18 changes: 12 additions & 6 deletions xarray/core/formatting_html.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
import uuid
from collections import OrderedDict
from functools import partial
from functools import lru_cache, partial
from html import escape
Comment on lines 1 to 4
Copy link
Member

Choose a reason for hiding this comment

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

isort seems to be complaining now


import pkg_resources

from .formatting import inline_variable_array_repr, short_data_repr

CSS_FILE_PATH = "/".join(("static", "css", "style.css"))
CSS_STYLE = pkg_resources.resource_string("xarray", CSS_FILE_PATH).decode("utf8")
STATIC_FILES = ("static/html/icons-svg-inline.html", "static/css/style.css")


ICONS_SVG_PATH = "/".join(("static", "html", "icons-svg-inline.html"))
ICONS_SVG = pkg_resources.resource_string("xarray", ICONS_SVG_PATH).decode("utf8")
@lru_cache(None)
def _load_static_files():
"""Lazily load the resource files into memory the first time they are needed
"""
return [
pkg_resources.resource_string("xarray", fname).decode("utf8")
for fname in STATIC_FILES
]


def short_data_repr_html(array):
Expand Down Expand Up @@ -233,9 +238,10 @@ def _obj_repr(obj, header_components, sections):
header = f"<div class='xr-header'>{''.join(h for h in header_components)}</div>"
sections = "".join(f"<li class='xr-section-item'>{s}</li>" for s in sections)

icons_svg, css_style = _load_static_files()
return (
"<div>"
f"{ICONS_SVG}<style>{CSS_STYLE}</style>"
f"{icons_svg}<style>{css_style}</style>"
f"<pre class='xr-text-repr-fallback'>{escape(repr(obj))}</pre>"
"<div class='xr-wrap' hidden>"
f"{header}"
Expand Down