Skip to content

Instantly share code, notes, and snippets.

@jian-en
Created July 27, 2017 03:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jian-en/46bdaa9a15f3c719bd95b7f8b7460473 to your computer and use it in GitHub Desktop.
Save jian-en/46bdaa9a15f3c719bd95b7f8b7460473 to your computer and use it in GitHub Desktop.
A method to replace if else if
from functools import singledispatch
from collections import abc
import numbers
import html
@singledispatch
def htmlize(obj):
content = html.escape(repr(obj))
return '<pre>{}</pre>'.format(content)
@htmlize.register(str)
def _(text):
content = html.escape(text).replace('\n', '<br>\n')
return '<p>{0}</p>'.format(content)
@htmlize.register(numbers.Integral)
def __(n):
return '<pre>{0} (0x{0:x})</pre>'.format(n)
@htmlize.register(tuple)
@htmlize.register(abc.MutableSequence)
def ___(seq):
inner = '</li>\n<li>'.join(htmlize(item) for item in seq)
return '<ul>\n<li>' + inner + '</li>\n</ul>'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment