r""" htmlize(): generic function example # tag::HTMLIZE_DEMO[] >>> htmlize({1, 2, 3}) # <1> '
{1, 2, 3}'
>>> htmlize(abs)
'<built-in function abs>' >>> htmlize('Heimlich & Co.\n- a game') # <2> '
Heimlich & Co.
\n- a game
42 (0x2a)' >>> print(htmlize(['alpha', 66, {3, 2, 1}])) # <4>
alpha
66 (0x42)
{1, 2, 3}True' >>> htmlize(fractions.Fraction(2, 3)) # <6> '
2/3' >>> htmlize(2/3) # <7> '
0.6666666666666666 (2/3)' >>> htmlize(decimal.Decimal('0.02380952')) '
0.02380952 (1/42)' # end::HTMLIZE_DEMO[] """ # tag::HTMLIZE[] from functools import singledispatch from collections import abc import fractions import decimal import html import numbers @singledispatch # <1> def htmlize(obj: object) -> str: content = html.escape(repr(obj)) return f'
{content}'
@htmlize.register # <2>
def _(text: str) -> str: # <3>
content = html.escape(text).replace('\n', '{content}
' @htmlize.register # <4> def _(seq: abc.Sequence) -> str: inner = '\n{n} (0x{n:x})'
@htmlize.register # <6>
def _(n: bool) -> str:
return f'{n}'
@htmlize.register(fractions.Fraction) # <7>
def _(x) -> str:
frac = fractions.Fraction(x)
return f'{frac.numerator}/{frac.denominator}'
@htmlize.register(decimal.Decimal) # <8>
@htmlize.register(float)
def _(x) -> str:
frac = fractions.Fraction(x).limit_denominator()
return f'{x} ({frac.numerator}/{frac.denominator})'
# end::HTMLIZE[]