The following link allows for a way to render an HTML URL inside a python3 print()
function within a Jupyter notebook code cell,
https://github.com/jupyterlab/jupyterlab/issues/7393#issue-510053776,
which defines a custom URL class,
"""URL Wrapper."""
from dataclasses import dataclass
@dataclass(frozen=True)
class Url:
"""Wrapper around a URL string to provide nice display in IPython environments."""
__url: str
def _repr_html_(self):
"""HTML link to this URL."""
return f'<a href="{self.__url}">{self.__url}</a>' # problem here (*)
def __str__(self):
"""Return the underlying string."""
return self.__url
The commentator notes that one must use str(url())
to achieve the desired result.
Unlike (I think) the now built-in rendering of this, I am trying to use this custom class thus:
linker = lambda my_string: str(Url('https://www.google.com/%s' % my_string))
print('URL for my_string is here',linker('search'))
I would like the linker('search')
to render as the string 'search' with the full hyperlink (https://www.google.com/search) behind. The built-in behaviour does not render 'search' but rather the full hyperlink, and I cannot find a way to successfully modify the custom class to do this. At line (*) above I have tried:
return f'<a href="{self.__url}">{self.__url}</a>'
return f'<a href="{self.__url}">{"test_text"}</a>'
etc. but so far in vain.
This answer helps a bit but doesn't explicitly use the print function as per my requirements: https://stackoverflow.com/a/43254984/1021819
What am I missing?