python-colorspace
python-colorspace copied to clipboard
Suggestion on showing colours in Jupyter notebooks
This is a great module and I wanted to suggest an enhancement.
In Jupyter Notebooks, an instance of an object is displayed (via IPython.display.display) in HTML according to the class _repr_html_ (and __repr__ as a fallback). As a result one can play with the styles attribute of an element say colouring text (color or the fill background).
from colorspace.colorlib import HCL, hexcols, colorobject
from copy import copy
def _repr_html_(self):
zelf = copy(self)
zelf.to('hex')
colhexes = zelf.colors()
styles= {'height': '50px',
'width':'50px',
'border':'5px solid grey',
'border-top':'5px solid white', # get some Helmholtz–Kohlrausch effect action!
'border-bottom':'5px solid black',
}
dict2style = lambda d: ';'.join(map(':'.join, d.items()))
# jupyter runs off bootstrap-3 formatting
divs = [f'<div class="col-md-1" style="{dict2style(styles)}; background:{colhex}"></div>' for colhex in colhexes]
return '<div class="row">{inner}</div>'.format(inner=''.join(divs))
colorobject._repr_html_ = _repr_html_
hexcols(['#002147', '#F3AD5B', '#F7601E'])

EDIT. This affects the behaviour of IPython.display.display(object) or the last object returned in the cells (_), not print(object), which still preferentially runs off __str__()