Skip to content

pymarkdown_builder

Python Markdown Builder.

MarkdownBuilder dataclass

A Markdown document builder with line and span writing modes.

Source code in src/pymarkdown_builder/builder.py
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
@dataclass
class MarkdownBuilder:
    """A Markdown document builder with line and span writing modes."""

    document: str = field(default="")
    """Content of the builder."""

    def write_lines(self, *lines: str) -> Self:
        """Joins the lines with double line breaks and appends to the document.

        Args:
            *lines (str): Unpacked iterable of lines to be appended.

        Returns:
            The builder instance.
        """
        joined_lines = "\n\n".join(lines)

        if self.document != "":
            self.document += "\n\n"

        self.document += joined_lines

        return self

    def write_spans(self, *spans: str) -> Self:
        """Joins the spans and appends to the document.

        Args:
            *spans (str): Unpacked iterable of spans to be appended.

        Returns:
            The builder instance.
        """
        joined_spans = "".join(spans)

        self.document += joined_spans

        return self

    def line_break(self) -> Self:
        """Appends a line break to the document.

        Returns:
            The builder instance.
        """
        self.document += "\n\n"

        return self

    def __str__(self) -> str:
        """Returns the content of the builder."""
        return self.document

    lines = write_lines
    spans = write_spans
    br = line_break

document: str = field(default='') class-attribute instance-attribute

Content of the builder.

__str__()

Returns the content of the builder.

Source code in src/pymarkdown_builder/builder.py
63
64
65
def __str__(self) -> str:
    """Returns the content of the builder."""
    return self.document

line_break()

Appends a line break to the document.

Returns:

Type Description
Self

The builder instance.

Source code in src/pymarkdown_builder/builder.py
53
54
55
56
57
58
59
60
61
def line_break(self) -> Self:
    """Appends a line break to the document.

    Returns:
        The builder instance.
    """
    self.document += "\n\n"

    return self

write_lines(*lines)

Joins the lines with double line breaks and appends to the document.

Parameters:

Name Type Description Default
*lines str

Unpacked iterable of lines to be appended.

()

Returns:

Type Description
Self

The builder instance.

Source code in src/pymarkdown_builder/builder.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def write_lines(self, *lines: str) -> Self:
    """Joins the lines with double line breaks and appends to the document.

    Args:
        *lines (str): Unpacked iterable of lines to be appended.

    Returns:
        The builder instance.
    """
    joined_lines = "\n\n".join(lines)

    if self.document != "":
        self.document += "\n\n"

    self.document += joined_lines

    return self

write_spans(*spans)

Joins the spans and appends to the document.

Parameters:

Name Type Description Default
*spans str

Unpacked iterable of spans to be appended.

()

Returns:

Type Description
Self

The builder instance.

Source code in src/pymarkdown_builder/builder.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def write_spans(self, *spans: str) -> Self:
    """Joins the spans and appends to the document.

    Args:
        *spans (str): Unpacked iterable of spans to be appended.

    Returns:
        The builder instance.
    """
    joined_spans = "".join(spans)

    self.document += joined_spans

    return self

Tokens

Markdown tokens. These are the building blocks of a markdown document.

Source code in src/pymarkdown_builder/tokens.py
  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
class Tokens:
    """Markdown tokens. These are the building blocks of a markdown document."""

    @staticmethod
    def heading(
        text: str,
        level: Optional[int] = None,
    ) -> str:
        """Creates a heading with the given level by by prepending the text with `#`.

        Args:
            text (str): The text of the heading.
            level (int): The level of the heading. Must be between `#!python 1` and `#!python 6`. If not provided, will use `#!python 1`.

        Examples:
            >>> Tokens.heading("Hello, world!")
            '# Hello, world!'
            >>> Tokens.heading("Hello, world!", 2)
            '## Hello, world!'
        """  # noqa: E501
        level = level if level is not None else 1

        if level < 1 or level > 6:
            raise ValueError("Level must be between 1 and 6.")

        return f"{'#' * level} {text}"

    @staticmethod
    def h1(
        text: str,
    ) -> str:
        """Creates a level 1 heading."""
        return Tokens.heading(text, 1)

    @staticmethod
    def h2(
        text: str,
    ) -> str:
        """Creates a level 2 heading."""
        return Tokens.heading(text, 2)

    @staticmethod
    def h3(
        text: str,
    ) -> str:
        """Creates a level 3 heading."""
        return Tokens.heading(text, 3)

    @staticmethod
    def h4(
        text: str,
    ) -> str:
        """Creates a level 4 heading."""
        return Tokens.heading(text, 4)

    @staticmethod
    def h5(
        text: str,
    ) -> str:
        """Creates a level 5 heading."""
        return Tokens.heading(text, 5)

    @staticmethod
    def h6(
        text: str,
    ) -> str:
        """Creates a level 6 heading."""
        return Tokens.heading(text, 6)

    @staticmethod
    def paragraph(
        text: str,
    ) -> str:
        """Creates a paragraph. In fact, will just return the text.

        Args:
            text (str): The text of the paragraph.

        Examples:
            >>> Tokens.paragraph("Hello, world!")
            'Hello, world!'
        """  # noqa: E501
        return text

    @staticmethod
    def quote(
        text: str,
    ) -> str:
        """Creates a quote by prepending the text with `>`.

        Args:
            text (str): The text of the quote.

        Examples:
            >>> Tokens.quote("Hello, world!")
            '> Hello, world!'
        """
        return f"> {text}"

    @staticmethod
    def horizontal_rule() -> str:
        """Creates a horizontal rule using `---`.

        Examples:
            >>> Tokens.horizontal_rule()
            '---'
        """
        return "---"

    @staticmethod
    def link(
        href: str,
        text: Optional[str] = None,
    ) -> str:
        """Creates a link with `[text](href)` syntax.

        Args:
            href (str): The href of the link.
            text (Optional[str]): The text to be shown as the link. If not provided, will use the `href` value.

        Examples:
            >>> Tokens.link("https://example.com")
            '[https://example.com](https://example.com)'
            >>> Tokens.link("https://example.com", "Example")
            '[Example](https://example.com)'
        """  # noqa: E501
        text = text or href

        return f"[{text}]({href})"

    @staticmethod
    def image(
        src: str,
        alt: Optional[str] = None,
        mouseover: Optional[str] = None,
    ):
        """Creates an image with `![alt](src "mouseover")` syntax.

        Args:
            src (str): The source of the image. Can be a path or a URL.
            alt (Optional[str]): The alt text. If not provided, will use an empty string.
            mouseover (Optional[str]): The mouseover text. If not provided, will not be set.

        Examples:
            >>> Tokens.image("https://example.com/image.png")
            '![](https://example.com/image.png)'
            >>> Tokens.image("https://example.com/image.png", "alt text", "mouseover text")
            '![alt text](https://example.com/image.png "mouseover text")'
        """  # noqa: E501
        alt = alt or ""

        if mouseover is None:
            mouseover = ""

        if mouseover != "":
            mouseover = f' "{mouseover}"'

        return f"![{alt}]({src}{mouseover})"

    @staticmethod
    def code_block(
        text: str,
        lang: Optional[str] = None,
    ) -> str:
        r"""Creates a code block with triple backticks syntax.

        Args:
            text (str): The text of the code block.
            lang (Optional[str]): The language of the code block. If not provided, will not be set.

        Examples:
            >>> Tokens.code_block("print('Hello, world!')", "python")
            "```python\nprint('Hello, world!')\n```"
        """  # noqa: E501
        lang = lang or ""

        return f"```{lang}\n{text}\n```"

    @staticmethod
    def unordered_list(
        *items: str,
    ) -> str:
        r"""Creates an unordered list by prepending each item with `- `.

        Args:
            *items (Iterable[str]): Unpacked iterable of items to be listed.

        Examples:
            >>> Tokens.unordered_list("Hello", "World")
            '- Hello\n- World'
        """
        return "\n".join(f"- {item}" for item in items)

    @staticmethod
    def ordered_list(
        *items: str,
    ) -> str:
        r"""Creates an ordered list by prepending each item with `1. `.

        Args:
            *items (Iterable[str]): Unpacked iterable of items to be listed.

        Examples:
            >>> Tokens.ordered_list("Hello", "World")
            '1. Hello\n1. World'
        """
        return "\n".join(f"1. {item}" for item in items)

    @staticmethod
    def table(
        *rows: Iterable[str],
    ) -> str:
        r"""Creates a table from an iterable of rows. Will separate cells using `|`, and separate the header and the body using `---`.

        Args:
            *rows (Iterable[str]): Unpacked iterable of rows. The first row is the header, and the rest are the body.

        Examples:
            >>> Tokens.table(["name", "age"], ["John", "20"], ["Jane", "19"])
            'name | age\n--- | ---\nJohn | 20\nJane | 19'
        """  # noqa: E501
        rows_iter = iter(rows)
        header_row = next(rows_iter, None)

        if header_row is None:
            return ""

        header_row = list(header_row)

        first_row = next(rows_iter, None)

        if first_row is None:
            return ""

        header_str = " | ".join(header_row)
        divider_str = " | ".join("---" for _ in header_row)
        body_str = "\n".join((" | ".join(row) for row in (first_row, *rows_iter)))

        return "\n".join((header_str, divider_str, body_str))

    @staticmethod
    def table_from_dicts(
        *dicts: Dict[str, str],
        header: Iterable[str] | None = None,
    ) -> str:
        r"""Creates a table from an iterable of rows. Will separate cells using `|`, and separate the header and the body using `---`.

        Args:
            *dicts (Dict[str, str]): Unpacked iterable of dicts. Each dict will be a row.
            header (Iterable[str] | None): Custom table header. If not provided, will use the keys of the first dict.

        Examples:
            >>> Tokens.table_from_dicts({"name": "John", "age": "20"}, {"name": "Jane", "age": "19"})
            'name | age\n--- | ---\nJohn | 20\nJane | 19'
        """  # noqa: E501
        dicts_iter = iter(dicts)
        first_row = next(dicts_iter, None)

        if first_row is None:
            return ""

        header = header or list(first_row.keys())
        body = ((value for value in row.values()) for row in (first_row, *dicts_iter))

        return Tokens.table(*(header, *body))

    # short tokens
    h = heading
    p = paragraph
    ul = unordered_list
    ol = ordered_list
    hr = horizontal_rule
    img = image

    bold = create_partial_token("**")
    """Creates bold text by wrapping the text with `**`.

    Args:
        text (str): The text to be set as bold.

    Examples:
        >>> Tokens.bold("Hello, world!")
        '**Hello, world!**'
        >>> Tokens.bold | "Hello, world!" | Tokens.bold
        '**Hello, world!**'
    """

    italic = create_partial_token("*")
    """Creates italic text by wrapping the text with `*`.

    Args:
        text (str): The text to be set as italic.

    Examples:
        >>> Tokens.italic("Hello, world!")
        '**Hello, world!**'
        >>> Tokens.italic | "Hello, world!" | Tokens.italic
        '*Hello, world!*'
    """

    code = create_partial_token("`")
    """Creates code text by wrapping the text with backticks ``` ` ```.

    Args:
        text (str): The text to be set as code.

    Examples:
        >>> Tokens.code("Hello, world!")
        '`Hello, world!`'
        >>> Tokens.code | "Hello, world!" | Tokens.code
        '`Hello, world!`'
    """

    strike = create_partial_token("~~")
    """Creates strike through text by wrapping the text with `~~`.

    Args:
        text (str): The text to striked.

    Examples:
        >>> Tokens.strike("Hello, world!")
        '~~Hello, world!~~'
        >>> Tokens.strike | "Hello, world!" | Tokens.strike
        '~~Hello, world!~~'
    """

bold = create_partial_token('**') class-attribute instance-attribute

Creates bold text by wrapping the text with **.

Parameters:

Name Type Description Default
text str

The text to be set as bold.

required

Examples:

>>> Tokens.bold("Hello, world!")
'**Hello, world!**'
>>> Tokens.bold | "Hello, world!" | Tokens.bold
'**Hello, world!**'

code = create_partial_token('`') class-attribute instance-attribute

Creates code text by wrapping the text with backticks `.

Parameters:

Name Type Description Default
text str

The text to be set as code.

required

Examples:

>>> Tokens.code("Hello, world!")
'`Hello, world!`'
>>> Tokens.code | "Hello, world!" | Tokens.code
'`Hello, world!`'

italic = create_partial_token('*') class-attribute instance-attribute

Creates italic text by wrapping the text with *.

Parameters:

Name Type Description Default
text str

The text to be set as italic.

required

Examples:

>>> Tokens.italic("Hello, world!")
'**Hello, world!**'
>>> Tokens.italic | "Hello, world!" | Tokens.italic
'*Hello, world!*'

strike = create_partial_token('~~') class-attribute instance-attribute

Creates strike through text by wrapping the text with ~~.

Parameters:

Name Type Description Default
text str

The text to striked.

required

Examples:

>>> Tokens.strike("Hello, world!")
'~~Hello, world!~~'
>>> Tokens.strike | "Hello, world!" | Tokens.strike
'~~Hello, world!~~'

code_block(text, lang=None) staticmethod

Creates a code block with triple backticks syntax.

Parameters:

Name Type Description Default
text str

The text of the code block.

required
lang Optional[str]

The language of the code block. If not provided, will not be set.

None

Examples:

>>> Tokens.code_block("print('Hello, world!')", "python")
"```python\nprint('Hello, world!')\n```"
Source code in src/pymarkdown_builder/tokens.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
@staticmethod
def code_block(
    text: str,
    lang: Optional[str] = None,
) -> str:
    r"""Creates a code block with triple backticks syntax.

    Args:
        text (str): The text of the code block.
        lang (Optional[str]): The language of the code block. If not provided, will not be set.

    Examples:
        >>> Tokens.code_block("print('Hello, world!')", "python")
        "```python\nprint('Hello, world!')\n```"
    """  # noqa: E501
    lang = lang or ""

    return f"```{lang}\n{text}\n```"

h1(text) staticmethod

Creates a level 1 heading.

Source code in src/pymarkdown_builder/tokens.py
35
36
37
38
39
40
@staticmethod
def h1(
    text: str,
) -> str:
    """Creates a level 1 heading."""
    return Tokens.heading(text, 1)

h2(text) staticmethod

Creates a level 2 heading.

Source code in src/pymarkdown_builder/tokens.py
42
43
44
45
46
47
@staticmethod
def h2(
    text: str,
) -> str:
    """Creates a level 2 heading."""
    return Tokens.heading(text, 2)

h3(text) staticmethod

Creates a level 3 heading.

Source code in src/pymarkdown_builder/tokens.py
49
50
51
52
53
54
@staticmethod
def h3(
    text: str,
) -> str:
    """Creates a level 3 heading."""
    return Tokens.heading(text, 3)

h4(text) staticmethod

Creates a level 4 heading.

Source code in src/pymarkdown_builder/tokens.py
56
57
58
59
60
61
@staticmethod
def h4(
    text: str,
) -> str:
    """Creates a level 4 heading."""
    return Tokens.heading(text, 4)

h5(text) staticmethod

Creates a level 5 heading.

Source code in src/pymarkdown_builder/tokens.py
63
64
65
66
67
68
@staticmethod
def h5(
    text: str,
) -> str:
    """Creates a level 5 heading."""
    return Tokens.heading(text, 5)

h6(text) staticmethod

Creates a level 6 heading.

Source code in src/pymarkdown_builder/tokens.py
70
71
72
73
74
75
@staticmethod
def h6(
    text: str,
) -> str:
    """Creates a level 6 heading."""
    return Tokens.heading(text, 6)

heading(text, level=None) staticmethod

Creates a heading with the given level by by prepending the text with #.

Parameters:

Name Type Description Default
text str

The text of the heading.

required
level int

The level of the heading. Must be between 1 and 6. If not provided, will use 1.

None

Examples:

>>> Tokens.heading("Hello, world!")
'# Hello, world!'
>>> Tokens.heading("Hello, world!", 2)
'## Hello, world!'
Source code in src/pymarkdown_builder/tokens.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@staticmethod
def heading(
    text: str,
    level: Optional[int] = None,
) -> str:
    """Creates a heading with the given level by by prepending the text with `#`.

    Args:
        text (str): The text of the heading.
        level (int): The level of the heading. Must be between `#!python 1` and `#!python 6`. If not provided, will use `#!python 1`.

    Examples:
        >>> Tokens.heading("Hello, world!")
        '# Hello, world!'
        >>> Tokens.heading("Hello, world!", 2)
        '## Hello, world!'
    """  # noqa: E501
    level = level if level is not None else 1

    if level < 1 or level > 6:
        raise ValueError("Level must be between 1 and 6.")

    return f"{'#' * level} {text}"

horizontal_rule() staticmethod

Creates a horizontal rule using ---.

Examples:

>>> Tokens.horizontal_rule()
'---'
Source code in src/pymarkdown_builder/tokens.py
107
108
109
110
111
112
113
114
115
@staticmethod
def horizontal_rule() -> str:
    """Creates a horizontal rule using `---`.

    Examples:
        >>> Tokens.horizontal_rule()
        '---'
    """
    return "---"

image(src, alt=None, mouseover=None) staticmethod

Creates an image with ![alt](src "mouseover") syntax.

Parameters:

Name Type Description Default
src str

The source of the image. Can be a path or a URL.

required
alt Optional[str]

The alt text. If not provided, will use an empty string.

None
mouseover Optional[str]

The mouseover text. If not provided, will not be set.

None

Examples:

>>> Tokens.image("https://example.com/image.png")
'![](https://example.com/image.png)'
>>> Tokens.image("https://example.com/image.png", "alt text", "mouseover text")
'![alt text](https://example.com/image.png "mouseover text")'
Source code in src/pymarkdown_builder/tokens.py
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
@staticmethod
def image(
    src: str,
    alt: Optional[str] = None,
    mouseover: Optional[str] = None,
):
    """Creates an image with `![alt](src "mouseover")` syntax.

    Args:
        src (str): The source of the image. Can be a path or a URL.
        alt (Optional[str]): The alt text. If not provided, will use an empty string.
        mouseover (Optional[str]): The mouseover text. If not provided, will not be set.

    Examples:
        >>> Tokens.image("https://example.com/image.png")
        '![](https://example.com/image.png)'
        >>> Tokens.image("https://example.com/image.png", "alt text", "mouseover text")
        '![alt text](https://example.com/image.png "mouseover text")'
    """  # noqa: E501
    alt = alt or ""

    if mouseover is None:
        mouseover = ""

    if mouseover != "":
        mouseover = f' "{mouseover}"'

    return f"![{alt}]({src}{mouseover})"

Creates a link with [text](href) syntax.

Parameters:

Name Type Description Default
href str

The href of the link.

required
text Optional[str]

The text to be shown as the link. If not provided, will use the href value.

None

Examples:

>>> Tokens.link("https://example.com")
'[https://example.com](https://example.com)'
>>> Tokens.link("https://example.com", "Example")
'[Example](https://example.com)'
Source code in src/pymarkdown_builder/tokens.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
@staticmethod
def link(
    href: str,
    text: Optional[str] = None,
) -> str:
    """Creates a link with `[text](href)` syntax.

    Args:
        href (str): The href of the link.
        text (Optional[str]): The text to be shown as the link. If not provided, will use the `href` value.

    Examples:
        >>> Tokens.link("https://example.com")
        '[https://example.com](https://example.com)'
        >>> Tokens.link("https://example.com", "Example")
        '[Example](https://example.com)'
    """  # noqa: E501
    text = text or href

    return f"[{text}]({href})"

ordered_list(*items) staticmethod

Creates an ordered list by prepending each item with 1..

Parameters:

Name Type Description Default
*items Iterable[str]

Unpacked iterable of items to be listed.

()

Examples:

>>> Tokens.ordered_list("Hello", "World")
'1. Hello\n1. World'
Source code in src/pymarkdown_builder/tokens.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
@staticmethod
def ordered_list(
    *items: str,
) -> str:
    r"""Creates an ordered list by prepending each item with `1. `.

    Args:
        *items (Iterable[str]): Unpacked iterable of items to be listed.

    Examples:
        >>> Tokens.ordered_list("Hello", "World")
        '1. Hello\n1. World'
    """
    return "\n".join(f"1. {item}" for item in items)

paragraph(text) staticmethod

Creates a paragraph. In fact, will just return the text.

Parameters:

Name Type Description Default
text str

The text of the paragraph.

required

Examples:

>>> Tokens.paragraph("Hello, world!")
'Hello, world!'
Source code in src/pymarkdown_builder/tokens.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
@staticmethod
def paragraph(
    text: str,
) -> str:
    """Creates a paragraph. In fact, will just return the text.

    Args:
        text (str): The text of the paragraph.

    Examples:
        >>> Tokens.paragraph("Hello, world!")
        'Hello, world!'
    """  # noqa: E501
    return text

quote(text) staticmethod

Creates a quote by prepending the text with >.

Parameters:

Name Type Description Default
text str

The text of the quote.

required

Examples:

>>> Tokens.quote("Hello, world!")
'> Hello, world!'
Source code in src/pymarkdown_builder/tokens.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
@staticmethod
def quote(
    text: str,
) -> str:
    """Creates a quote by prepending the text with `>`.

    Args:
        text (str): The text of the quote.

    Examples:
        >>> Tokens.quote("Hello, world!")
        '> Hello, world!'
    """
    return f"> {text}"

table(*rows) staticmethod

Creates a table from an iterable of rows. Will separate cells using |, and separate the header and the body using ---.

Parameters:

Name Type Description Default
*rows Iterable[str]

Unpacked iterable of rows. The first row is the header, and the rest are the body.

()

Examples:

>>> Tokens.table(["name", "age"], ["John", "20"], ["Jane", "19"])
'name | age\n--- | ---\nJohn | 20\nJane | 19'
Source code in src/pymarkdown_builder/tokens.py
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
@staticmethod
def table(
    *rows: Iterable[str],
) -> str:
    r"""Creates a table from an iterable of rows. Will separate cells using `|`, and separate the header and the body using `---`.

    Args:
        *rows (Iterable[str]): Unpacked iterable of rows. The first row is the header, and the rest are the body.

    Examples:
        >>> Tokens.table(["name", "age"], ["John", "20"], ["Jane", "19"])
        'name | age\n--- | ---\nJohn | 20\nJane | 19'
    """  # noqa: E501
    rows_iter = iter(rows)
    header_row = next(rows_iter, None)

    if header_row is None:
        return ""

    header_row = list(header_row)

    first_row = next(rows_iter, None)

    if first_row is None:
        return ""

    header_str = " | ".join(header_row)
    divider_str = " | ".join("---" for _ in header_row)
    body_str = "\n".join((" | ".join(row) for row in (first_row, *rows_iter)))

    return "\n".join((header_str, divider_str, body_str))

table_from_dicts(*dicts, header=None) staticmethod

Creates a table from an iterable of rows. Will separate cells using |, and separate the header and the body using ---.

Parameters:

Name Type Description Default
*dicts Dict[str, str]

Unpacked iterable of dicts. Each dict will be a row.

()
header Iterable[str] | None

Custom table header. If not provided, will use the keys of the first dict.

None

Examples:

>>> Tokens.table_from_dicts({"name": "John", "age": "20"}, {"name": "Jane", "age": "19"})
'name | age\n--- | ---\nJohn | 20\nJane | 19'
Source code in src/pymarkdown_builder/tokens.py
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
@staticmethod
def table_from_dicts(
    *dicts: Dict[str, str],
    header: Iterable[str] | None = None,
) -> str:
    r"""Creates a table from an iterable of rows. Will separate cells using `|`, and separate the header and the body using `---`.

    Args:
        *dicts (Dict[str, str]): Unpacked iterable of dicts. Each dict will be a row.
        header (Iterable[str] | None): Custom table header. If not provided, will use the keys of the first dict.

    Examples:
        >>> Tokens.table_from_dicts({"name": "John", "age": "20"}, {"name": "Jane", "age": "19"})
        'name | age\n--- | ---\nJohn | 20\nJane | 19'
    """  # noqa: E501
    dicts_iter = iter(dicts)
    first_row = next(dicts_iter, None)

    if first_row is None:
        return ""

    header = header or list(first_row.keys())
    body = ((value for value in row.values()) for row in (first_row, *dicts_iter))

    return Tokens.table(*(header, *body))

unordered_list(*items) staticmethod

Creates an unordered list by prepending each item with -.

Parameters:

Name Type Description Default
*items Iterable[str]

Unpacked iterable of items to be listed.

()

Examples:

>>> Tokens.unordered_list("Hello", "World")
'- Hello\n- World'
Source code in src/pymarkdown_builder/tokens.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
@staticmethod
def unordered_list(
    *items: str,
) -> str:
    r"""Creates an unordered list by prepending each item with `- `.

    Args:
        *items (Iterable[str]): Unpacked iterable of items to be listed.

    Examples:
        >>> Tokens.unordered_list("Hello", "World")
        '- Hello\n- World'
    """
    return "\n".join(f"- {item}" for item in items)

create_partial_token(open_tag, close_tag=None)

Creates a partial token.

Parameters:

Name Type Description Default
open_tag str

The string that will be prepended to the text.

required
close_tag Optional[str]

The string that will be appended to the text. If not provided, will use the open_tag value.

None
Source code in src/pymarkdown_builder/partial_tokens.py
115
116
117
118
119
120
121
122
123
124
125
def create_partial_token(
    open_tag: str,
    close_tag: Optional[str] = None,
):
    """Creates a partial token.

    Args:
        open_tag (str): The string that will be prepended to the text.
        close_tag (Optional[str]): The string that will be appended to the text. If not provided, will use the `open_tag` value.
    """  # noqa: E501
    return PartialToken(open_tag, close_tag)