可扩展html representation for python objects.
hrepr的Python项目详细描述
hrepr是一个为python创建html表示的包 物体。它可以输出到Jupyter笔记本电脑,还可以生成 具有选择对象表示的独立页。
有关更多示例,请参见examples.ipynb笔记本,但请记住 Github显示不正确。
安装
hrepr至少需要python 3.6
$ pip3 install hrepr
用法
fromhreprimporthreprobj={'potatoes':[1,2,3],'bananas':{'cantaloups':8}}# Print the HTML representation of objprint(hrepr(obj))# Wrap the representation in <html><body> tags and embed the default# css style files to produce a standalone page.print(hrepr(obj).as_page())
在jupyter笔记本中,直接返回hrepr(obj)。
自定义表示
可以使用 __hrepr__方法,如果需要,则 __hrepr_resources__类的方法。不依赖于hrepr 有必要:
classRedGreen:def__init__(self,r,g):self.r=rself.g=g@classmethoddef__hrepr_resources__(cls,H):returnH.style(''' .red { background-color: red; } .green { background-color: green; } ''')def__hrepr__(self,H,hrepr):returnH.div(H.div['red'](hrepr(self.r)),H.div['green'](hrepr(self.g)))
__hrepr__接收两个参数:
- H是html生成器,它具有简单的接口:
H.tag['klass',...](child,..., attr=value, ...)创建
标签<tag class=klass attr=value>child</tag>。您可以添加更多
类、属性和子类,即书写是合法的
H.a['cls1'](href='blah')['cls2']('hello', attr=value)
- 使用H.raw(string)插入未转换的字符串(例如文字 html)
- 使用H.inline(...)连接子级而不换行 在标签上。
- hrepr是一个函数,可以递归调用它来获取 对象字段的表示。
__hrepr_resources__是可选的,但是如果定义了它,它应该 返回应插入^{tt17}的标记的一个或一个列表$ 页面的节,以便正确设置表示格式。 这些标记可以是<style>标记、<script>标记或<link>标记。
__hrepr_short__也是可选的,应该返回一个表示 具有常量(小)大小的,例如类的值name 字段、数组的长度或其他内容。
配置表示法
hrepr可以接受任意数量的关键字参数。其中一些是 特别处理,而其他则隐藏在传递给的hrepr对象中 __hrepr__方法,可用于实现 自定义元素。以下键是特殊的(它们的使用示例可以 在examples.ipynb笔记本中找到:
- max_depth限制将显示多少层嵌套对象。 超过这个深度,对象用它们的^{tt21}表示$ 方法。
- type_处理程序将一个或多个类型映射到具有签名的函数 (obj, H, hrepr) -> Tag,用于生成 显示。这些处理程序重写__hrepr__。
- type_handlers_short:相同,但表示形式较短。
- resources是具有签名(H,) -> [Tag]的函数的一个或一个列表, 这意味着它们接受H构造函数并返回一个或多个style 或者全局需要的script或link标记。
- preprocess是一个带有签名的函数(obj, hrepr) -> obj。它 必须返回要显示的替代对象,而不是obj。
- 后处理是一个带有签名(obj, tag, H, hrepr) -> Tag的函数。 它必须返回一个可选的或修改过的Tag对象才能显示。为了 例如,它可以返回tag['highlight'],这是要添加的语法 将'highlight'类转换为Tag,在这种情况下,后处理器 表面上突出显示了相应的对象。如果后处理器 返回None,对象将由tag表示,就像 如果没有后处理器。
自定义hrepr
您还可以通过子类化 HRepr或StdHRepr类(两者之间的区别是 后者定义了几种python类型的默认表示 例如list或dict,而前者没有)。
子类可以覆盖以下函数和字段:
- global_resources(H)应将一个或一个标记列表返回给 插入<head>。
- __default_handlers__()应返回将类型关联到的dict 手印处理者真实的handler(obj, H, hrepr)。当给予 一个特定类型的对象,hrepr将首先在那里查找它。
- __call__(obj)是主表示函数,将 为每个要表示的对象递归调用。
fromhreprimportStdHReprclassMyRepr(StdHRepr):def__default_handlers__(self):dh=super().__default__handlers__()return{**dh,int:self.repr_int}defglobal_resources(self,H):returnH.style(".my-integer { color: fuchsia; }")defrepr_int(self,n,H,hrepr):returnH.span['my-integer']('The number ',str(n))defmyrepr(obj):# Call hrepr_with_resources to attach the resources to the# return value, otherwise .as_page() will not work as# intended.returnMyRepr().hrepr_with_resources(obj)print(myrepr(10))# <span class="my-integer">The number 10</span>print(myrepr(10).as_page())# This will include the style