Skip to content

Commit

Permalink
Convert attribute and dimension names to strings when generating HTML…
Browse files Browse the repository at this point in the history
… repr (#5149)

* Convert attribute keys to strings when generating HTML repr.

The standard repr() already handled non-string attribute names, but the
HTML formatter failed when trying to escape HTML entitites in non-string
names. This just calls str() before escape(). It also includes tests for
Dataset, DataArray and Variable.

Related issue is #5146.

* Convert dimension names to strings when generating HTML reprs.

Not currently working for datasets as dimension sorting does not yet
handle non-str keys.

Co-authored-by: Keewis <keewis@posteo.de>
  • Loading branch information
bcbnz and keewis authored May 4, 2021
1 parent f2a3318 commit 1c198a1
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
4 changes: 2 additions & 2 deletions xarray/core/formatting_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def format_dims(dims, coord_names):
}

dims_li = "".join(
f"<li><span{dim_css_map[dim]}>" f"{escape(dim)}</span>: {size}</li>"
f"<li><span{dim_css_map[dim]}>" f"{escape(str(dim))}</span>: {size}</li>"
for dim, size in dims.items()
)

Expand All @@ -48,7 +48,7 @@ def format_dims(dims, coord_names):

def summarize_attrs(attrs):
attrs_dl = "".join(
f"<dt><span>{escape(k)} :</span></dt>" f"<dd>{escape(str(v))}</dd>"
f"<dt><span>{escape(str(k))} :</span></dt>" f"<dd>{escape(str(v))}</dd>"
for k, v in attrs.items()
)

Expand Down
26 changes: 26 additions & 0 deletions xarray/tests/test_formatting_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,3 +181,29 @@ def test_variable_repr_html():
# Just test that something reasonable was produced.
assert html.startswith("<div") and html.endswith("</div>")
assert "xarray.Variable" in html


def test_repr_of_nonstr_dataset(dataset):
ds = dataset.copy()
ds.attrs[1] = "Test value"
ds[2] = ds["tmin"]
formatted = fh.dataset_repr(ds)
assert "<dt><span>1 :</span></dt><dd>Test value</dd>" in formatted
assert "<div class='xr-var-name'><span>2</span>" in formatted


def test_repr_of_nonstr_dataarray(dataarray):
da = dataarray.rename(dim_0=15)
da.attrs[1] = "value"
formatted = fh.array_repr(da)
assert "<dt><span>1 :</span></dt><dd>value</dd>" in formatted
assert "<li><span>15</span>: 4</li>" in formatted


def test_nonstr_variable_repr_html():
v = xr.Variable(["time", 10], [[1, 2, 3], [4, 5, 6]], {22: "bar"})
assert hasattr(v, "_repr_html_")
with xr.set_options(display_style="html"):
html = v._repr_html_().strip()
assert "<dt><span>22 :</span></dt><dd>bar</dd>" in html
assert "<li><span>10</span>: 3</li></ul>" in html

0 comments on commit 1c198a1

Please sign in to comment.