rich-struct 0.3.2__tar.gz → 0.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {rich_struct-0.3.2 → rich_struct-0.4.0}/PKG-INFO +16 -5
- {rich_struct-0.3.2 → rich_struct-0.4.0}/README.md +12 -3
- {rich_struct-0.3.2 → rich_struct-0.4.0}/pyproject.toml +3 -2
- {rich_struct-0.3.2 → rich_struct-0.4.0}/rich_struct/__init__.py +68 -1
- {rich_struct-0.3.2 → rich_struct-0.4.0}/tests/test_print.py +49 -0
- {rich_struct-0.3.2 → rich_struct-0.4.0}/.gitignore +0 -0
- {rich_struct-0.3.2 → rich_struct-0.4.0}/LICENSE +0 -0
- {rich_struct-0.3.2 → rich_struct-0.4.0}/rich_struct/py.typed +0 -0
- {rich_struct-0.3.2 → rich_struct-0.4.0}/rich_struct/tables.py +0 -0
- {rich_struct-0.3.2 → rich_struct-0.4.0}/rich_struct/themes.py +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: rich-struct
|
|
3
|
-
Version: 0.
|
|
4
|
-
Summary: rich.print with 25 themes (Midnight Slate, Tokyo Night, Dracula, Nord, ...) and print_md/json/yaml/xml/obj/table helpers
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: rich.print with 25 themes (Midnight Slate, Tokyo Night, Dracula, Nord, ...) and print_md/html/json/yaml/xml/obj/table/list helpers
|
|
5
5
|
Project-URL: Homepage, https://github.com/wiertmir/rich-struct
|
|
6
6
|
Project-URL: Issues, https://github.com/wiertmir/rich-struct/issues
|
|
7
7
|
Author: Mirek Wiertel
|
|
@@ -13,22 +13,24 @@ Classifier: Programming Language :: Python :: 3
|
|
|
13
13
|
Classifier: Topic :: Terminals
|
|
14
14
|
Requires-Python: >=3.9
|
|
15
15
|
Requires-Dist: rich>=13
|
|
16
|
+
Provides-Extra: html
|
|
17
|
+
Requires-Dist: markdownify; extra == 'html'
|
|
16
18
|
Provides-Extra: yaml
|
|
17
19
|
Requires-Dist: pyyaml; extra == 'yaml'
|
|
18
20
|
Description-Content-Type: text/markdown
|
|
19
21
|
|
|
20
22
|
# rich-struct
|
|
21
23
|
|
|
22
|
-
[`rich`](https://github.com/Textualize/rich)'s `print`, with 25 themes (23 popular editor themes and two originals) and helpers for Markdown, JSON, YAML, XML, Python objects and tables (lists, numpy arrays, pandas DataFrames and Series).
|
|
24
|
+
[`rich`](https://github.com/Textualize/rich)'s `print`, with 25 themes (23 popular editor themes and two originals) and helpers for Markdown, HTML, JSON, YAML, XML, Python objects and tables (lists, numpy arrays, pandas DataFrames and Series).
|
|
23
25
|
|
|
24
26
|
```sh
|
|
25
|
-
pip install rich-struct # add [yaml] to dump objects with print_yaml
|
|
27
|
+
pip install rich-struct # add [yaml] to dump objects with print_yaml, [html] for print_html
|
|
26
28
|
```
|
|
27
29
|
|
|
28
30
|
```python
|
|
29
31
|
from rich.markdown import Markdown
|
|
30
32
|
from rich.theme import Theme
|
|
31
|
-
from rich_struct import ThemeName, print, print_md, print_json, print_yaml, print_xml, print_obj, print_syntax, print_table
|
|
33
|
+
from rich_struct import ThemeName, print, print_md, print_json, print_yaml, print_xml, print_obj, print_syntax, print_table, print_list, print_html
|
|
32
34
|
|
|
33
35
|
print("[bold]hello[/bold]", {"a": 1}) # drop-in rich.print, Midnight Slate by default
|
|
34
36
|
print(Markdown("## Printing structs"), theme=ThemeName.DRACULA)
|
|
@@ -37,10 +39,12 @@ print_md("# Title\n\n```python\nprint('hi')\n```")
|
|
|
37
39
|
print_json({"a": [1, 2, None]}, theme="Nord") # enum value as a string works too
|
|
38
40
|
print_yaml("a: 1\nb: [x, y]")
|
|
39
41
|
print_xml("<a><b c='d'/></a>")
|
|
42
|
+
print_html("<h1>Title</h1><p>Some <b>bold</b> text</p>") # rendered, not its tags
|
|
40
43
|
print_obj(my_dataclass, theme=ThemeName.GITHUB_LIGHT)
|
|
41
44
|
print_syntax("SELECT 1", "sql") # any pygments lexer
|
|
42
45
|
print_table(df, title="Sales") # DataFrame, Series, numpy array, list...
|
|
43
46
|
print(df) # arrays and frames become tables in print too
|
|
47
|
+
print_list(series, head_tail_only=True) # [1, 2.5, 'text', ... 98, 99]: list, array, Series
|
|
44
48
|
|
|
45
49
|
print_md("# Mine", theme=Theme({"markdown.h1": "bold magenta", "syntax.keyword": "red"}))
|
|
46
50
|
```
|
|
@@ -105,6 +109,13 @@ Numbers are right-aligned, floats in a column share their decimals, and missing
|
|
|
105
109
|
Long data shows its head and tail around a `…` gap, and columns that don't fit the terminal width go into the gap as well.
|
|
106
110
|
`to_table(data)` returns the renderable instead of printing it. numpy and pandas are not dependencies.
|
|
107
111
|
|
|
112
|
+
## Lists
|
|
113
|
+
|
|
114
|
+
`print_list(data, wrap=True, head_tail_only=False, head_tail_size=100)` prints a list, tuple, `array.array`, numpy array or pandas `Series` as one sequence: `[123, 1444.555, 'Test text', 4345.666]`.
|
|
115
|
+
|
|
116
|
+
It wraps at the terminal width; `wrap=False` keeps it on one line.
|
|
117
|
+
`head_tail_only=True` shows only the first and last `head_tail_size` elements, with a highlighted ` ... ` between them.
|
|
118
|
+
|
|
108
119
|
## Themes
|
|
109
120
|
|
|
110
121
|
| Dark | Light |
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
# rich-struct
|
|
2
2
|
|
|
3
|
-
[`rich`](https://github.com/Textualize/rich)'s `print`, with 25 themes (23 popular editor themes and two originals) and helpers for Markdown, JSON, YAML, XML, Python objects and tables (lists, numpy arrays, pandas DataFrames and Series).
|
|
3
|
+
[`rich`](https://github.com/Textualize/rich)'s `print`, with 25 themes (23 popular editor themes and two originals) and helpers for Markdown, HTML, JSON, YAML, XML, Python objects and tables (lists, numpy arrays, pandas DataFrames and Series).
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
|
-
pip install rich-struct # add [yaml] to dump objects with print_yaml
|
|
6
|
+
pip install rich-struct # add [yaml] to dump objects with print_yaml, [html] for print_html
|
|
7
7
|
```
|
|
8
8
|
|
|
9
9
|
```python
|
|
10
10
|
from rich.markdown import Markdown
|
|
11
11
|
from rich.theme import Theme
|
|
12
|
-
from rich_struct import ThemeName, print, print_md, print_json, print_yaml, print_xml, print_obj, print_syntax, print_table
|
|
12
|
+
from rich_struct import ThemeName, print, print_md, print_json, print_yaml, print_xml, print_obj, print_syntax, print_table, print_list, print_html
|
|
13
13
|
|
|
14
14
|
print("[bold]hello[/bold]", {"a": 1}) # drop-in rich.print, Midnight Slate by default
|
|
15
15
|
print(Markdown("## Printing structs"), theme=ThemeName.DRACULA)
|
|
@@ -18,10 +18,12 @@ print_md("# Title\n\n```python\nprint('hi')\n```")
|
|
|
18
18
|
print_json({"a": [1, 2, None]}, theme="Nord") # enum value as a string works too
|
|
19
19
|
print_yaml("a: 1\nb: [x, y]")
|
|
20
20
|
print_xml("<a><b c='d'/></a>")
|
|
21
|
+
print_html("<h1>Title</h1><p>Some <b>bold</b> text</p>") # rendered, not its tags
|
|
21
22
|
print_obj(my_dataclass, theme=ThemeName.GITHUB_LIGHT)
|
|
22
23
|
print_syntax("SELECT 1", "sql") # any pygments lexer
|
|
23
24
|
print_table(df, title="Sales") # DataFrame, Series, numpy array, list...
|
|
24
25
|
print(df) # arrays and frames become tables in print too
|
|
26
|
+
print_list(series, head_tail_only=True) # [1, 2.5, 'text', ... 98, 99]: list, array, Series
|
|
25
27
|
|
|
26
28
|
print_md("# Mine", theme=Theme({"markdown.h1": "bold magenta", "syntax.keyword": "red"}))
|
|
27
29
|
```
|
|
@@ -86,6 +88,13 @@ Numbers are right-aligned, floats in a column share their decimals, and missing
|
|
|
86
88
|
Long data shows its head and tail around a `…` gap, and columns that don't fit the terminal width go into the gap as well.
|
|
87
89
|
`to_table(data)` returns the renderable instead of printing it. numpy and pandas are not dependencies.
|
|
88
90
|
|
|
91
|
+
## Lists
|
|
92
|
+
|
|
93
|
+
`print_list(data, wrap=True, head_tail_only=False, head_tail_size=100)` prints a list, tuple, `array.array`, numpy array or pandas `Series` as one sequence: `[123, 1444.555, 'Test text', 4345.666]`.
|
|
94
|
+
|
|
95
|
+
It wraps at the terminal width; `wrap=False` keeps it on one line.
|
|
96
|
+
`head_tail_only=True` shows only the first and last `head_tail_size` elements, with a highlighted ` ... ` between them.
|
|
97
|
+
|
|
89
98
|
## Themes
|
|
90
99
|
|
|
91
100
|
| Dark | Light |
|
|
@@ -4,8 +4,8 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "rich-struct"
|
|
7
|
-
version = "0.
|
|
8
|
-
description = "rich.print with 25 themes (Midnight Slate, Tokyo Night, Dracula, Nord, ...) and print_md/json/yaml/xml/obj/table helpers"
|
|
7
|
+
version = "0.4.0"
|
|
8
|
+
description = "rich.print with 25 themes (Midnight Slate, Tokyo Night, Dracula, Nord, ...) and print_md/html/json/yaml/xml/obj/table/list helpers"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.9"
|
|
11
11
|
license = "MIT"
|
|
@@ -21,6 +21,7 @@ classifiers = [
|
|
|
21
21
|
|
|
22
22
|
[project.optional-dependencies]
|
|
23
23
|
yaml = ["pyyaml"]
|
|
24
|
+
html = ["markdownify"]
|
|
24
25
|
|
|
25
26
|
[project.urls]
|
|
26
27
|
Homepage = "https://github.com/wiertmir/rich-struct"
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"""Themed drop-in extension of ``rich.print``."""
|
|
2
2
|
|
|
3
|
+
import re
|
|
3
4
|
import xml.etree.ElementTree as ET
|
|
4
5
|
from typing import IO, Any, Optional, Union
|
|
5
6
|
|
|
@@ -11,6 +12,7 @@ from rich.padding import Padding
|
|
|
11
12
|
from rich.pretty import Pretty
|
|
12
13
|
from rich.protocol import is_renderable
|
|
13
14
|
from rich.syntax import Syntax
|
|
15
|
+
from rich.text import Text
|
|
14
16
|
from rich.theme import Theme
|
|
15
17
|
|
|
16
18
|
from .tables import is_array, to_table
|
|
@@ -22,7 +24,9 @@ __all__ = [
|
|
|
22
24
|
"ThemeName",
|
|
23
25
|
"ThemeType",
|
|
24
26
|
"print",
|
|
27
|
+
"print_html",
|
|
25
28
|
"print_json",
|
|
29
|
+
"print_list",
|
|
26
30
|
"print_md",
|
|
27
31
|
"print_obj",
|
|
28
32
|
"print_syntax",
|
|
@@ -89,7 +93,8 @@ def print(
|
|
|
89
93
|
elif isinstance(obj, Syntax):
|
|
90
94
|
# ponytail: Syntax has no public theme setter; rebuild the object if rich renames this
|
|
91
95
|
obj._theme = code_theme
|
|
92
|
-
|
|
96
|
+
# width goes to the Console: Console.print can only narrow it, print_list needs it wider
|
|
97
|
+
console = Console(theme=rich_theme, file=file, width=kwargs.pop("width", None))
|
|
93
98
|
base = rich_theme.styles.get("background")
|
|
94
99
|
if background and base and console.color_system:
|
|
95
100
|
if objects and all(isinstance(obj, Pretty) for obj in objects):
|
|
@@ -111,6 +116,27 @@ def print_md(markdown: Optional[str], *, theme: Optional[ThemeType] = None, **kw
|
|
|
111
116
|
print(Markdown(markdown), theme=theme, **kwargs)
|
|
112
117
|
|
|
113
118
|
|
|
119
|
+
def _code_language(el: Any) -> str:
|
|
120
|
+
"""The language of a ``<pre>`` block, from a ``language-python`` style class on it or its ``<code>``."""
|
|
121
|
+
classes = [c for tag in (el, el.find("code")) if tag for c in tag.get("class") or []]
|
|
122
|
+
return next((c.partition("-")[2] for c in classes if c.startswith(("language-", "lang-"))), "")
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def print_html(html: Optional[str], *, theme: Optional[ThemeType] = None, **kwargs: Any) -> None:
|
|
126
|
+
"""Print HTML rendered (headings, lists, tables, links...), not its tags (needs ``rich-struct[html]``).
|
|
127
|
+
|
|
128
|
+
The page is converted to Markdown, so it gets the theme's Markdown styles;
|
|
129
|
+
CSS, scripts and anything else Markdown has no word for are dropped.
|
|
130
|
+
"""
|
|
131
|
+
if html is None:
|
|
132
|
+
return print(None, theme=theme, **kwargs)
|
|
133
|
+
from markdownify import markdownify
|
|
134
|
+
|
|
135
|
+
# ponytail: regex drops what must not show as text; fine short of a <script> holding "</script>"
|
|
136
|
+
html = re.sub(r"(?is)<(head|script|style|template)\b.*?</\1\s*>|<!--.*?-->", "", html)
|
|
137
|
+
print_md(markdownify(html, heading_style="ATX", code_language_callback=_code_language), theme=theme, **kwargs)
|
|
138
|
+
|
|
139
|
+
|
|
114
140
|
def print_syntax(
|
|
115
141
|
code: Optional[str], lexer: str, *, theme: Optional[ThemeType] = None, **kwargs: Any
|
|
116
142
|
) -> None:
|
|
@@ -178,3 +204,44 @@ def print_table(
|
|
|
178
204
|
return print(None, theme=theme, **kwargs)
|
|
179
205
|
table = to_table(data, title=title, max_rows=max_rows, max_cols=max_cols)
|
|
180
206
|
print(table, theme=theme, **kwargs)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def print_list(
|
|
210
|
+
data: Any,
|
|
211
|
+
*,
|
|
212
|
+
wrap: bool = True,
|
|
213
|
+
head_tail_only: bool = False,
|
|
214
|
+
head_tail_size: int = 100,
|
|
215
|
+
theme: Optional[ThemeType] = None,
|
|
216
|
+
**kwargs: Any,
|
|
217
|
+
) -> None:
|
|
218
|
+
"""Print a list, array, numpy array or pandas Series as a sequence: ``[1, 2.5, 'text']``.
|
|
219
|
+
|
|
220
|
+
Long sequences wrap at the terminal width unless ``wrap=False``. With
|
|
221
|
+
``head_tail_only``, only the first and last ``head_tail_size`` elements are
|
|
222
|
+
shown, around a highlighted " ... " gap.
|
|
223
|
+
"""
|
|
224
|
+
if data is None:
|
|
225
|
+
return print(None, theme=theme, **kwargs)
|
|
226
|
+
if head_tail_size < 1:
|
|
227
|
+
raise ValueError("head_tail_size must be at least 1")
|
|
228
|
+
if not (hasattr(data, "tolist") or isinstance(data, (list, tuple))):
|
|
229
|
+
data = list(data) # sets, generators...
|
|
230
|
+
parts = [data]
|
|
231
|
+
if head_tail_only and len(data) > 2 * head_tail_size:
|
|
232
|
+
rows = getattr(data, "iloc", data) # pandas slices by position only through iloc
|
|
233
|
+
parts = [rows[:head_tail_size], rows[len(data) - head_tail_size :]]
|
|
234
|
+
highlight = _ObjectHighlighter()
|
|
235
|
+
text = Text().append("[", style="repr.brace")
|
|
236
|
+
for i, part in enumerate(parts):
|
|
237
|
+
if i:
|
|
238
|
+
text.append(" ... ", style="bold reverse")
|
|
239
|
+
# tolist() turns numpy and pandas scalars into plain Python ones, also inside a plain list
|
|
240
|
+
values = part.tolist() if hasattr(part, "tolist") else part
|
|
241
|
+
values = (v.tolist() if hasattr(v, "tolist") else v for v in values)
|
|
242
|
+
text.append_text(highlight(", ".join(map(repr, values))))
|
|
243
|
+
text.append("]", style="repr.brace")
|
|
244
|
+
if not wrap:
|
|
245
|
+
# one line however long: the terminal, not rich, decides what to do with it
|
|
246
|
+
kwargs["width"] = max(text.cell_len, Console(file=kwargs.get("file")).width)
|
|
247
|
+
print(text, theme=theme, **kwargs)
|
|
@@ -199,3 +199,52 @@ def test_numpy_and_pandas_tables():
|
|
|
199
199
|
assert "2 rows × 3 columns" in render(rt.print, df)
|
|
200
200
|
assert "shape (2,)" in render(rt.print, np.array([1, 2]))
|
|
201
201
|
assert render(rt.print, [1, 2]) == "[1, 2]\n"
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def test_print_list():
|
|
205
|
+
assert render(rt.print_list, [123, 1444.555, "Test text", 4345.666]) == "[123, 1444.555, 'Test text', 4345.666]\n"
|
|
206
|
+
assert render(rt.print_list, array("d", [1.0, 2.5])) == "[1.0, 2.5]\n"
|
|
207
|
+
assert render(rt.print_list, None) == "None\n"
|
|
208
|
+
long = list(range(60))
|
|
209
|
+
assert len(render(rt.print_list, long).splitlines()) > 1
|
|
210
|
+
assert render(rt.print_list, long, wrap=False) == f"{long}\n"
|
|
211
|
+
assert render(rt.print_list, range(10), head_tail_only=True, head_tail_size=2) == "[0, 1 ... 8, 9]\n"
|
|
212
|
+
assert render(rt.print_list, [1, 2, 3, 4], head_tail_only=True, head_tail_size=2) == "[1, 2, 3, 4]\n"
|
|
213
|
+
with pytest.raises(ValueError):
|
|
214
|
+
rt.print_list([1], head_tail_size=0)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def test_print_list_gap_is_highlighted(monkeypatch):
|
|
218
|
+
monkeypatch.setenv("FORCE_COLOR", "1")
|
|
219
|
+
out = render(rt.print_list, list(range(10)), head_tail_only=True, head_tail_size=2)
|
|
220
|
+
assert out.count("\x1b[1;7;") == 1 and " ... " in out # only the gap is bold + reverse
|
|
221
|
+
long = list(range(60))
|
|
222
|
+
assert Text.from_ansi(render(rt.print_list, long, wrap=False)).plain.rstrip() == str(long) # not cropped
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def test_print_list_numpy_and_pandas():
|
|
226
|
+
np = pytest.importorskip("numpy")
|
|
227
|
+
pd = pytest.importorskip("pandas")
|
|
228
|
+
assert render(rt.print_list, np.array([1.5, 2.0])) == "[1.5, 2.0]\n"
|
|
229
|
+
assert render(rt.print_list, [np.float64(1.5), "a"]) == "[1.5, 'a']\n"
|
|
230
|
+
series = pd.Series([10, 20, 30, 40, 50], index=[3, 4, 0, 1, 2])
|
|
231
|
+
assert render(rt.print_list, series, head_tail_only=True, head_tail_size=1) == "[10 ... 50]\n"
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def test_print_html_renders_instead_of_showing_tags(monkeypatch):
|
|
235
|
+
pytest.importorskip("markdownify")
|
|
236
|
+
html = """<html><head><title>T</title><style>p {color: red}</style></head><body>
|
|
237
|
+
<!-- hidden --><script>alert(1)</script>
|
|
238
|
+
<h1>Title</h1><p>Some <b>bold</b> and <a href="https://e.com">a link</a>.</p>
|
|
239
|
+
<ul><li>one</li><li>two</li></ul>
|
|
240
|
+
<pre><code class="language-python">def f(): pass</code></pre>
|
|
241
|
+
<table><tr><th>name</th></tr><tr><td>Ada</td></tr></table></body></html>"""
|
|
242
|
+
out = render(rt.print_html, html)
|
|
243
|
+
for shown in ("Title", "Some bold and a link.", "• one", "def f(): pass", "name", "Ada"):
|
|
244
|
+
assert shown in out
|
|
245
|
+
for hidden in ("<", "color", "alert", "hidden", "**"):
|
|
246
|
+
assert hidden not in out
|
|
247
|
+
assert render(rt.print_html, None) == "None\n"
|
|
248
|
+
monkeypatch.setenv("FORCE_COLOR", "1")
|
|
249
|
+
monkeypatch.setenv("COLORTERM", "truecolor")
|
|
250
|
+
assert "38;2;167;139;250" in render(rt.print_html, html) # the code block is highlighted as Python
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|