Created
November 6, 2018 08:18
-
-
Save eric-wieser/56b1ae377ad3ffa8c8180c75ea91c08a to your computer and use it in GitHub Desktop.
A super janky example of how _repr_html_ could be implemented
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def _html_repr_helper(contents, index=()): | |
dims_left = contents.ndim - len(index) | |
if dims_left == 0: | |
s = contents[index] | |
else: | |
s = ''.join(_html_repr_helper(contents, index + (i,)) for i in range(contents.shape[len(index)])) | |
return "<div class='numpy-array-ndim-{} numpy-array-ndim-m{}' title='[{}]'>{}</div>".format( | |
len(index), dims_left, | |
','.join('{}'.format(i) for i in (index + (':',) * dims_left)), | |
s, | |
) | |
class Pretty(np.ndarray): | |
def _repr_html_(self): | |
css = """ | |
.numpy-array { | |
display: inline-block; | |
} | |
.numpy-array div { | |
border: 1px solid black; | |
margin: 2px; | |
display: flex; | |
flex-direction: column; | |
flex: 1 1 auto; | |
} | |
.numpy-array div:hover { | |
border: 1px solid red; | |
} | |
.numpy-array div.numpy-array-ndim-m1 { | |
flex-direction: row; | |
} | |
.numpy-array div.numpy-array-ndim-m0 { | |
padding: 5px; | |
} | |
""" | |
return """<div class='numpy-array'><style>{}</style>{}</div>""".format(css, _html_repr_helper(self)) | |
def make_pretty(x): | |
return np.asarray(x).view(Pretty) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment