前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python singledispatch函数分发器

python singledispatch函数分发器

作者头像
用户5760343
发布2019-08-02 11:41:55
5070
发布2019-08-02 11:41:55
举报
文章被收录于专栏:sktj

r""" htmlize(): generic function example

BEGIN HTMLIZE_DEMO

htmlize({1, 2, 3}) # <1> '<pre>{1, 2, 3}</pre>' htmlize(abs) '<pre><built-in function abs></pre>' htmlize('Heimlich & Co.\n- a game') # <2> '<p>Heimlich & Co. \n- a game</p>' htmlize(42) # <3> '<pre>42 (0x2a)</pre>' print(htmlize(['alpha', 66, {3, 2, 1}])) # <4> <ul> <li><p>alpha</p></li> <li><pre>66 (0x42)</pre></li> <li><pre>{1, 2, 3}</pre></li> </ul>

END HTMLIZE_DEMO

"""

BEGIN HTMLIZE

from functools import singledispatch from collections import abc import numbers import html

@singledispatch # <1> def htmlize(obj): content = html.escape(repr(obj)) return '<pre>{}</pre>'.format(content)

@htmlize.register(str) # <2> def _(text): # <3> content = html.escape(text).replace('\n', ' \n') return '<p>{0}</p>'.format(content)

@htmlize.register(numbers.Integral) # <4> def _(n): return '<pre>{0} (0x{0:x})</pre>'.format(n)

@htmlize.register(tuple) # <5> @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>'

END HTMLIZE

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.07.31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • BEGIN HTMLIZE_DEMO
  • END HTMLIZE_DEMO
  • BEGIN HTMLIZE
  • END HTMLIZE
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档