1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
|
%global _empty_manifest_terminate_build 0
Name: python-hrepr
Version: 0.5.1
Release: 1
Summary: Extensible HTML representation for Python objects.
License: MIT
URL: https://github.com/breuleux/hrepr
Source0: https://mirrors.aliyun.com/pypi/web/packages/a4/e8/46fc52b4762291881a0c9c9f9b96d721d5d874254c88d776b80efb910191/hrepr-0.5.1.tar.gz
BuildArch: noarch
Requires: python3-ovld
%description
# hrepr
`hrepr` outputs HTML/pretty representations for Python objects.
✅ Nice, colourful representations of lists, dicts, dataclasses, booleans...<br/>
✅ Ridiculously extensible and configurable<br/>
✅ Handles recursive data structures<br/>
✅ Compatible with Jupyter notebooks<br/>
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr1.png" width="400px"><img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr2.png" width="400px">
I suggest studying the example file to learn `hrepr`:
* `python examples/exhibit.py > exhibit.html` (and then view the HTML file)
Also see the Jupyter notebook at `examples/Basics.ipynb`, but keep in mind that GitHub can't display it properly because of the injected styles/scripts.
## Install
```python
pip install hrepr
```
## Usage
```python
from hrepr import hrepr
obj = {'potatoes': [1, 2, 3], 'bananas': {'cantaloups': 8}}
# Print the HTML representation of obj
print(hrepr(obj))
# Wrap the representation in <html><body> tags and embed the default
# css style files in a standalone page, which is saved to obj.html
hrepr.page(obj, file="obj.html")
```
In a Jupyter Notebook, you can return `hrepr(obj)` from any cell and it will show its representation for you. You can also write `display_html(hrepr(obj))`.
## Custom representations
A custom representation for an object can be defined using the following three methods (it is not necessary to define all of them, only those that are relevant to your case):
* `__hrepr__(self, H, hrepr)` returns the normal HTML representation.
* Use `H.span["some-class"](some-content, some_attr=some_value)` to generate HTML.
* Use `hrepr(self.x)` to generate the representation for some subfield `x`.
* `hrepr.config` contains any keyword arguments given in the top level call to `hrepr`. For instance, if you call `hrepr(obj, blah=3)`, then `hrepr.config.blah == 3` in all calls to `__hrepr__` down the line (the default value for all keys is `None`).
* `__hrepr_short__(self, H, hrepr)` returns a *short* representation, ideally of a constant size.
* The output of this method is used when we hit max depth, or for repeated references.
* Only include bare minimum information. Short means short.
* `__hrepr_resources__(cls, H)` is a **classmethod** that returns resources common to all instances of the class (typically a stylesheet or a script).
* When generating a page, the resources will go in `<head>`.
* You can return a list of resources.
No dependency on `hrepr` is necessary.
For example:
```python
class Person:
def __init__(self, name, age, job):
self.name = name
self.age = age
self.job = job
@classmethod
def __hrepr_resources__(cls, H):
# Note: you might need to add "!important" next to some rules if
# they conflict with defaults from hrepr's own CSS.
return H.style("""
.person {
background: magenta !important;
border-color: magenta !important;
}
.person-short { font-weight: bold; color: green; }
""")
def __hrepr__(self, H, hrepr):
# hrepr.make.instance is a helper to show a table with a header that
# describes some kind of object
return hrepr.make.instance(
title=self.name,
fields=[["age", self.age], ["job", self.job]],
delimiter=" ↦ ",
type="person",
)
def __hrepr_short__(self, H, hrepr):
return H.span["person-short"](self.name)
```
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr3.png" width="600px">
## References
`hrepr` can handle circular references. Furthermore, if an object is found at several places in a structure, only the first occurrence will be printed in full, and any other will be a numeric reference mapped to the short representation for the object. It looks like this:
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr4.png" width="600px">
The `shortrefs` and `norefs` configuration keys control the representation of references:
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr5.png" width="600px">
`norefs` is ignored when there are circular references.
## HTML generation
Generate HTML using the `H` parameter to `__hrepr__`, or import it and use it directly:
```python
from hrepr import H
html = H.span["bear"](
"Only ", H.b("YOU"), " can prevent forest fires!",
style="color: brown;"
)
print(html)
# <span class="bear" style="color: brown;">Only <b>YOU</b> can prevent forest fires!</span>
```
`H` can be built incrementally: if you have an element, you can call it to add children, index it to add classes, and so on. For instance:
```python
from hrepr import H
html = H.span()
html = html("Only ")
html = html(style="color: brown;")["bear"]
html = html(H.b("YOU"), " can prevent forest fires!")
print(html)
# <span class="bear" style="color: brown;">Only <b>YOU</b> can prevent forest fires!</span>
```
This can be handy if you want to tweak generated HTML a little. For example, `hrepr(obj)["fox"]` will tack on the class `fox` to the representation of the object.
### Helpers
* `hrepr.make.instance(title, fields, delimiter=None, type=None)`: formats the fields like a dataclass, with title on top.
* `hrepr.make.bracketed(body, start, end, type=None)`: formats the body with the specified start/end bracket.
### Constructed elements
To make it a bit easier to include and use JavaScript libraries, you can use the special `__constructor` attribute.
For example, you can load Plotly and create a plot like this:
```python
def Plot(data):
return H.div(
__constructor={
"script": "https://cdn.plot.ly/plotly-latest.min.js",
"symbol": "Plotly.newPlot",
"options": [{"x": list(range(len(data))), "y": list(data)}],
}
)
print(Plot([math.sin(x / 10) for x in range(100)]))
```
The above will:
* Load the specified script.
* Get the `Plotly.newPlot` function in the global namespace.
* Call it with the `div` element as the first argument, and the `options` as the second argument.
It will look like this:
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr6.png" width="600px">
### Modules
Another example, this time using ESM (modules):
```python
node = H.div(
style="width:500px;height:500px;border:1px solid black;",
__constructor={
"module": "https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.23.0/cytoscape.esm.min.js",
"arguments": {
"container": H.self(),
"elements": [
{"data": {"id": "A"}},
{"data": {"id": "B"}},
{"data": {"id": "C"}},
{"data": {"source": "A", "target": "B"}},
{"data": {"source": "B", "target": "C"}},
{"data": {"source": "C", "target": "A"}},
],
"style": cystyle,
"layout": {"name": "cose"},
},
},
)
print(node)
```
The above will:
* Import the specified module.
* Call the module's default export with `arguments`.
* Note the use of `H.self()` to refer to the target `div` in the arguments.
If you wish to use a non-default export, set the `symbol` key in the `__constructor` attribute to the name of the export you want.
## Customize hrepr
### Mixins
If you want to *really* customize hrepr, you can use mixins. They look like a bit of black magic, but they're simple enough:
```python
# ovld is one of the dependencies of hrepr
from ovld import ovld, extend_super, has_attribute, OvldMC
from hrepr import hrepr
class MyMixin(metaclass=OvldMC):
# Change the representation of integers
@extend_super
def hrepr_resources(self, cls: int):
# Note: in hrepr_resources, cls is the int type, not an integer
return self.H.style(".my-integer { color: fuchsia; }")
@extend_super
def hrepr(self, n: int):
return self.H.span["my-integer"]("The number ", str(n))
# Specially handle any object with a "quack" method
def hrepr(self, duck: has_attribute("quack")):
return self.H.span("🦆")
```
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr7.png" width="600px">
The annotation for a rule can either be a type, `ovld.has_attribute`, or pretty much any function wrapped with the `ovld.meta` decorator, as long as the function operates on classes. See the documentation for [ovld](https://github.com/breuleux/ovld#other-features) for more information.
And yes, you can define `hrepr` multiple times inside the class, as long as they have distinct annotations and you inherit from `Hrepr`. You can also define `hrepr_short` or `hrepr_resources` the same way.
### Postprocessors
`hrepr` can be given a postprocessor that is called on the representation of any object. You can use this to do things like highlighting specific objects:
```python
from hrepr import H
style = H.style(".highlight { border: 3px solid red !important; }")
def highlight(x):
def postprocess(element, obj, hrepr):
if obj == x:
# Adds the "highlight" class and attaches a style
return element["highlight"].fill(resources=style)
else:
return element
return postprocess
hrepr([1, 2, [3, 4, 2]], postprocess=highlight(2))
```
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr8.png" width="600px">
### hrepr variants
To put this all together, you can create a *variant* of `hrepr`:
```python
hrepr2 = hrepr.variant(mixins=MyMixin, postprocess=highlight(2))
hrepr2([1, 2, 3]) # Will use the mixins and postprocessor
```
### Configure the hrepr function itself
Alternatively, you can configure the main `hrepr`:
```python
hrepr.configure(mixins=MyMixin, postprocess=highlight(2))
```
But keep in mind that unlike the variant, the above will modify `hrepr` for everything else as well.
%package -n python3-hrepr
Summary: Extensible HTML representation for Python objects.
Provides: python-hrepr
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-hrepr
# hrepr
`hrepr` outputs HTML/pretty representations for Python objects.
✅ Nice, colourful representations of lists, dicts, dataclasses, booleans...<br/>
✅ Ridiculously extensible and configurable<br/>
✅ Handles recursive data structures<br/>
✅ Compatible with Jupyter notebooks<br/>
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr1.png" width="400px"><img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr2.png" width="400px">
I suggest studying the example file to learn `hrepr`:
* `python examples/exhibit.py > exhibit.html` (and then view the HTML file)
Also see the Jupyter notebook at `examples/Basics.ipynb`, but keep in mind that GitHub can't display it properly because of the injected styles/scripts.
## Install
```python
pip install hrepr
```
## Usage
```python
from hrepr import hrepr
obj = {'potatoes': [1, 2, 3], 'bananas': {'cantaloups': 8}}
# Print the HTML representation of obj
print(hrepr(obj))
# Wrap the representation in <html><body> tags and embed the default
# css style files in a standalone page, which is saved to obj.html
hrepr.page(obj, file="obj.html")
```
In a Jupyter Notebook, you can return `hrepr(obj)` from any cell and it will show its representation for you. You can also write `display_html(hrepr(obj))`.
## Custom representations
A custom representation for an object can be defined using the following three methods (it is not necessary to define all of them, only those that are relevant to your case):
* `__hrepr__(self, H, hrepr)` returns the normal HTML representation.
* Use `H.span["some-class"](some-content, some_attr=some_value)` to generate HTML.
* Use `hrepr(self.x)` to generate the representation for some subfield `x`.
* `hrepr.config` contains any keyword arguments given in the top level call to `hrepr`. For instance, if you call `hrepr(obj, blah=3)`, then `hrepr.config.blah == 3` in all calls to `__hrepr__` down the line (the default value for all keys is `None`).
* `__hrepr_short__(self, H, hrepr)` returns a *short* representation, ideally of a constant size.
* The output of this method is used when we hit max depth, or for repeated references.
* Only include bare minimum information. Short means short.
* `__hrepr_resources__(cls, H)` is a **classmethod** that returns resources common to all instances of the class (typically a stylesheet or a script).
* When generating a page, the resources will go in `<head>`.
* You can return a list of resources.
No dependency on `hrepr` is necessary.
For example:
```python
class Person:
def __init__(self, name, age, job):
self.name = name
self.age = age
self.job = job
@classmethod
def __hrepr_resources__(cls, H):
# Note: you might need to add "!important" next to some rules if
# they conflict with defaults from hrepr's own CSS.
return H.style("""
.person {
background: magenta !important;
border-color: magenta !important;
}
.person-short { font-weight: bold; color: green; }
""")
def __hrepr__(self, H, hrepr):
# hrepr.make.instance is a helper to show a table with a header that
# describes some kind of object
return hrepr.make.instance(
title=self.name,
fields=[["age", self.age], ["job", self.job]],
delimiter=" ↦ ",
type="person",
)
def __hrepr_short__(self, H, hrepr):
return H.span["person-short"](self.name)
```
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr3.png" width="600px">
## References
`hrepr` can handle circular references. Furthermore, if an object is found at several places in a structure, only the first occurrence will be printed in full, and any other will be a numeric reference mapped to the short representation for the object. It looks like this:
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr4.png" width="600px">
The `shortrefs` and `norefs` configuration keys control the representation of references:
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr5.png" width="600px">
`norefs` is ignored when there are circular references.
## HTML generation
Generate HTML using the `H` parameter to `__hrepr__`, or import it and use it directly:
```python
from hrepr import H
html = H.span["bear"](
"Only ", H.b("YOU"), " can prevent forest fires!",
style="color: brown;"
)
print(html)
# <span class="bear" style="color: brown;">Only <b>YOU</b> can prevent forest fires!</span>
```
`H` can be built incrementally: if you have an element, you can call it to add children, index it to add classes, and so on. For instance:
```python
from hrepr import H
html = H.span()
html = html("Only ")
html = html(style="color: brown;")["bear"]
html = html(H.b("YOU"), " can prevent forest fires!")
print(html)
# <span class="bear" style="color: brown;">Only <b>YOU</b> can prevent forest fires!</span>
```
This can be handy if you want to tweak generated HTML a little. For example, `hrepr(obj)["fox"]` will tack on the class `fox` to the representation of the object.
### Helpers
* `hrepr.make.instance(title, fields, delimiter=None, type=None)`: formats the fields like a dataclass, with title on top.
* `hrepr.make.bracketed(body, start, end, type=None)`: formats the body with the specified start/end bracket.
### Constructed elements
To make it a bit easier to include and use JavaScript libraries, you can use the special `__constructor` attribute.
For example, you can load Plotly and create a plot like this:
```python
def Plot(data):
return H.div(
__constructor={
"script": "https://cdn.plot.ly/plotly-latest.min.js",
"symbol": "Plotly.newPlot",
"options": [{"x": list(range(len(data))), "y": list(data)}],
}
)
print(Plot([math.sin(x / 10) for x in range(100)]))
```
The above will:
* Load the specified script.
* Get the `Plotly.newPlot` function in the global namespace.
* Call it with the `div` element as the first argument, and the `options` as the second argument.
It will look like this:
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr6.png" width="600px">
### Modules
Another example, this time using ESM (modules):
```python
node = H.div(
style="width:500px;height:500px;border:1px solid black;",
__constructor={
"module": "https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.23.0/cytoscape.esm.min.js",
"arguments": {
"container": H.self(),
"elements": [
{"data": {"id": "A"}},
{"data": {"id": "B"}},
{"data": {"id": "C"}},
{"data": {"source": "A", "target": "B"}},
{"data": {"source": "B", "target": "C"}},
{"data": {"source": "C", "target": "A"}},
],
"style": cystyle,
"layout": {"name": "cose"},
},
},
)
print(node)
```
The above will:
* Import the specified module.
* Call the module's default export with `arguments`.
* Note the use of `H.self()` to refer to the target `div` in the arguments.
If you wish to use a non-default export, set the `symbol` key in the `__constructor` attribute to the name of the export you want.
## Customize hrepr
### Mixins
If you want to *really* customize hrepr, you can use mixins. They look like a bit of black magic, but they're simple enough:
```python
# ovld is one of the dependencies of hrepr
from ovld import ovld, extend_super, has_attribute, OvldMC
from hrepr import hrepr
class MyMixin(metaclass=OvldMC):
# Change the representation of integers
@extend_super
def hrepr_resources(self, cls: int):
# Note: in hrepr_resources, cls is the int type, not an integer
return self.H.style(".my-integer { color: fuchsia; }")
@extend_super
def hrepr(self, n: int):
return self.H.span["my-integer"]("The number ", str(n))
# Specially handle any object with a "quack" method
def hrepr(self, duck: has_attribute("quack")):
return self.H.span("🦆")
```
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr7.png" width="600px">
The annotation for a rule can either be a type, `ovld.has_attribute`, or pretty much any function wrapped with the `ovld.meta` decorator, as long as the function operates on classes. See the documentation for [ovld](https://github.com/breuleux/ovld#other-features) for more information.
And yes, you can define `hrepr` multiple times inside the class, as long as they have distinct annotations and you inherit from `Hrepr`. You can also define `hrepr_short` or `hrepr_resources` the same way.
### Postprocessors
`hrepr` can be given a postprocessor that is called on the representation of any object. You can use this to do things like highlighting specific objects:
```python
from hrepr import H
style = H.style(".highlight { border: 3px solid red !important; }")
def highlight(x):
def postprocess(element, obj, hrepr):
if obj == x:
# Adds the "highlight" class and attaches a style
return element["highlight"].fill(resources=style)
else:
return element
return postprocess
hrepr([1, 2, [3, 4, 2]], postprocess=highlight(2))
```
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr8.png" width="600px">
### hrepr variants
To put this all together, you can create a *variant* of `hrepr`:
```python
hrepr2 = hrepr.variant(mixins=MyMixin, postprocess=highlight(2))
hrepr2([1, 2, 3]) # Will use the mixins and postprocessor
```
### Configure the hrepr function itself
Alternatively, you can configure the main `hrepr`:
```python
hrepr.configure(mixins=MyMixin, postprocess=highlight(2))
```
But keep in mind that unlike the variant, the above will modify `hrepr` for everything else as well.
%package help
Summary: Development documents and examples for hrepr
Provides: python3-hrepr-doc
%description help
# hrepr
`hrepr` outputs HTML/pretty representations for Python objects.
✅ Nice, colourful representations of lists, dicts, dataclasses, booleans...<br/>
✅ Ridiculously extensible and configurable<br/>
✅ Handles recursive data structures<br/>
✅ Compatible with Jupyter notebooks<br/>
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr1.png" width="400px"><img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr2.png" width="400px">
I suggest studying the example file to learn `hrepr`:
* `python examples/exhibit.py > exhibit.html` (and then view the HTML file)
Also see the Jupyter notebook at `examples/Basics.ipynb`, but keep in mind that GitHub can't display it properly because of the injected styles/scripts.
## Install
```python
pip install hrepr
```
## Usage
```python
from hrepr import hrepr
obj = {'potatoes': [1, 2, 3], 'bananas': {'cantaloups': 8}}
# Print the HTML representation of obj
print(hrepr(obj))
# Wrap the representation in <html><body> tags and embed the default
# css style files in a standalone page, which is saved to obj.html
hrepr.page(obj, file="obj.html")
```
In a Jupyter Notebook, you can return `hrepr(obj)` from any cell and it will show its representation for you. You can also write `display_html(hrepr(obj))`.
## Custom representations
A custom representation for an object can be defined using the following three methods (it is not necessary to define all of them, only those that are relevant to your case):
* `__hrepr__(self, H, hrepr)` returns the normal HTML representation.
* Use `H.span["some-class"](some-content, some_attr=some_value)` to generate HTML.
* Use `hrepr(self.x)` to generate the representation for some subfield `x`.
* `hrepr.config` contains any keyword arguments given in the top level call to `hrepr`. For instance, if you call `hrepr(obj, blah=3)`, then `hrepr.config.blah == 3` in all calls to `__hrepr__` down the line (the default value for all keys is `None`).
* `__hrepr_short__(self, H, hrepr)` returns a *short* representation, ideally of a constant size.
* The output of this method is used when we hit max depth, or for repeated references.
* Only include bare minimum information. Short means short.
* `__hrepr_resources__(cls, H)` is a **classmethod** that returns resources common to all instances of the class (typically a stylesheet or a script).
* When generating a page, the resources will go in `<head>`.
* You can return a list of resources.
No dependency on `hrepr` is necessary.
For example:
```python
class Person:
def __init__(self, name, age, job):
self.name = name
self.age = age
self.job = job
@classmethod
def __hrepr_resources__(cls, H):
# Note: you might need to add "!important" next to some rules if
# they conflict with defaults from hrepr's own CSS.
return H.style("""
.person {
background: magenta !important;
border-color: magenta !important;
}
.person-short { font-weight: bold; color: green; }
""")
def __hrepr__(self, H, hrepr):
# hrepr.make.instance is a helper to show a table with a header that
# describes some kind of object
return hrepr.make.instance(
title=self.name,
fields=[["age", self.age], ["job", self.job]],
delimiter=" ↦ ",
type="person",
)
def __hrepr_short__(self, H, hrepr):
return H.span["person-short"](self.name)
```
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr3.png" width="600px">
## References
`hrepr` can handle circular references. Furthermore, if an object is found at several places in a structure, only the first occurrence will be printed in full, and any other will be a numeric reference mapped to the short representation for the object. It looks like this:
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr4.png" width="600px">
The `shortrefs` and `norefs` configuration keys control the representation of references:
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr5.png" width="600px">
`norefs` is ignored when there are circular references.
## HTML generation
Generate HTML using the `H` parameter to `__hrepr__`, or import it and use it directly:
```python
from hrepr import H
html = H.span["bear"](
"Only ", H.b("YOU"), " can prevent forest fires!",
style="color: brown;"
)
print(html)
# <span class="bear" style="color: brown;">Only <b>YOU</b> can prevent forest fires!</span>
```
`H` can be built incrementally: if you have an element, you can call it to add children, index it to add classes, and so on. For instance:
```python
from hrepr import H
html = H.span()
html = html("Only ")
html = html(style="color: brown;")["bear"]
html = html(H.b("YOU"), " can prevent forest fires!")
print(html)
# <span class="bear" style="color: brown;">Only <b>YOU</b> can prevent forest fires!</span>
```
This can be handy if you want to tweak generated HTML a little. For example, `hrepr(obj)["fox"]` will tack on the class `fox` to the representation of the object.
### Helpers
* `hrepr.make.instance(title, fields, delimiter=None, type=None)`: formats the fields like a dataclass, with title on top.
* `hrepr.make.bracketed(body, start, end, type=None)`: formats the body with the specified start/end bracket.
### Constructed elements
To make it a bit easier to include and use JavaScript libraries, you can use the special `__constructor` attribute.
For example, you can load Plotly and create a plot like this:
```python
def Plot(data):
return H.div(
__constructor={
"script": "https://cdn.plot.ly/plotly-latest.min.js",
"symbol": "Plotly.newPlot",
"options": [{"x": list(range(len(data))), "y": list(data)}],
}
)
print(Plot([math.sin(x / 10) for x in range(100)]))
```
The above will:
* Load the specified script.
* Get the `Plotly.newPlot` function in the global namespace.
* Call it with the `div` element as the first argument, and the `options` as the second argument.
It will look like this:
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr6.png" width="600px">
### Modules
Another example, this time using ESM (modules):
```python
node = H.div(
style="width:500px;height:500px;border:1px solid black;",
__constructor={
"module": "https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.23.0/cytoscape.esm.min.js",
"arguments": {
"container": H.self(),
"elements": [
{"data": {"id": "A"}},
{"data": {"id": "B"}},
{"data": {"id": "C"}},
{"data": {"source": "A", "target": "B"}},
{"data": {"source": "B", "target": "C"}},
{"data": {"source": "C", "target": "A"}},
],
"style": cystyle,
"layout": {"name": "cose"},
},
},
)
print(node)
```
The above will:
* Import the specified module.
* Call the module's default export with `arguments`.
* Note the use of `H.self()` to refer to the target `div` in the arguments.
If you wish to use a non-default export, set the `symbol` key in the `__constructor` attribute to the name of the export you want.
## Customize hrepr
### Mixins
If you want to *really* customize hrepr, you can use mixins. They look like a bit of black magic, but they're simple enough:
```python
# ovld is one of the dependencies of hrepr
from ovld import ovld, extend_super, has_attribute, OvldMC
from hrepr import hrepr
class MyMixin(metaclass=OvldMC):
# Change the representation of integers
@extend_super
def hrepr_resources(self, cls: int):
# Note: in hrepr_resources, cls is the int type, not an integer
return self.H.style(".my-integer { color: fuchsia; }")
@extend_super
def hrepr(self, n: int):
return self.H.span["my-integer"]("The number ", str(n))
# Specially handle any object with a "quack" method
def hrepr(self, duck: has_attribute("quack")):
return self.H.span("🦆")
```
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr7.png" width="600px">
The annotation for a rule can either be a type, `ovld.has_attribute`, or pretty much any function wrapped with the `ovld.meta` decorator, as long as the function operates on classes. See the documentation for [ovld](https://github.com/breuleux/ovld#other-features) for more information.
And yes, you can define `hrepr` multiple times inside the class, as long as they have distinct annotations and you inherit from `Hrepr`. You can also define `hrepr_short` or `hrepr_resources` the same way.
### Postprocessors
`hrepr` can be given a postprocessor that is called on the representation of any object. You can use this to do things like highlighting specific objects:
```python
from hrepr import H
style = H.style(".highlight { border: 3px solid red !important; }")
def highlight(x):
def postprocess(element, obj, hrepr):
if obj == x:
# Adds the "highlight" class and attaches a style
return element["highlight"].fill(resources=style)
else:
return element
return postprocess
hrepr([1, 2, [3, 4, 2]], postprocess=highlight(2))
```
<img src="https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr8.png" width="600px">
### hrepr variants
To put this all together, you can create a *variant* of `hrepr`:
```python
hrepr2 = hrepr.variant(mixins=MyMixin, postprocess=highlight(2))
hrepr2([1, 2, 3]) # Will use the mixins and postprocessor
```
### Configure the hrepr function itself
Alternatively, you can configure the main `hrepr`:
```python
hrepr.configure(mixins=MyMixin, postprocess=highlight(2))
```
But keep in mind that unlike the variant, the above will modify `hrepr` for everything else as well.
%prep
%autosetup -n hrepr-0.5.1
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "\"/%h/%f.gz\"\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-hrepr -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Tue Jun 20 2023 Python_Bot <Python_Bot@openeuler.org> - 0.5.1-1
- Package Spec generated
|