Skip to content

reprexlite.formatting

Attributes

formatter_registry: Dict[str, Type[Formatter]] = {} module-attribute

Registry of formatters keyed by venue keywords.

Classes

Advertisement

Class for generating the advertisement note for reprexlite.

Attributes:

Name Type Description
timestamp str

Timestamp of instance instantiation

version str

Version of reprexlite

Source code in reprexlite/formatting.py
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
class Advertisement:
    """Class for generating the advertisement note for reprexlite.

    Attributes:
        timestamp (str): Timestamp of instance instantiation
        version (str): Version of reprexlite
    """

    pkg = "reprexlite"
    url = "https://github.com/jayqi/reprexlite"

    def __init__(self):
        self.timestamp = datetime.now().astimezone().strftime("%Y-%m-%d %H:%M %Z")
        self.version = f"v{__version__}"

    def markdown(self) -> str:
        """Render reprexlite advertisement in GitHub Flavored Markdown."""
        return f"<sup>Created at {self.timestamp} by [{self.pkg}]({self.url}) {self.version}</sup>"

    def html(self) -> str:
        """Render reprexlite advertisement in HTML."""
        return (
            f"<p><sup>Created at {self.timestamp} by "
            f'<a href="{self.url}">{self.pkg}</a> {self.version}</sup></p>'
        )

    def code_comment(self) -> str:
        """Render reprexlite advertisement as a comment in Python code."""
        return f"# {self.text()}"

    def text(self) -> str:
        """Render reprexlite advertisement in plain text."""
        return f"Created at {self.timestamp} by {self.pkg} {self.version} <{self.url}>"

Functions

code_comment() -> str

Render reprexlite advertisement as a comment in Python code.

Source code in reprexlite/formatting.py
281
282
283
def code_comment(self) -> str:
    """Render reprexlite advertisement as a comment in Python code."""
    return f"# {self.text()}"
html() -> str

Render reprexlite advertisement in HTML.

Source code in reprexlite/formatting.py
274
275
276
277
278
279
def html(self) -> str:
    """Render reprexlite advertisement in HTML."""
    return (
        f"<p><sup>Created at {self.timestamp} by "
        f'<a href="{self.url}">{self.pkg}</a> {self.version}</sup></p>'
    )
markdown() -> str

Render reprexlite advertisement in GitHub Flavored Markdown.

Source code in reprexlite/formatting.py
270
271
272
def markdown(self) -> str:
    """Render reprexlite advertisement in GitHub Flavored Markdown."""
    return f"<sup>Created at {self.timestamp} by [{self.pkg}]({self.url}) {self.version}</sup>"
text() -> str

Render reprexlite advertisement in plain text.

Source code in reprexlite/formatting.py
285
286
287
def text(self) -> str:
    """Render reprexlite advertisement in plain text."""
    return f"Created at {self.timestamp} by {self.pkg} {self.version} <{self.url}>"

Formatter

Bases: ABC

Abstract base class for a reprex formatter. Concrete subclasses should implement the formatting logic appropriate to a specific venue for sharing. Call str(...) on an instance to return the formatted reprex.

Attributes:

Name Type Description
default_advertise bool

Whether to render reprexlite advertisement by default

meta FormatterMeta

Contains metadata for the formatter, such as label text and an example

Source code in reprexlite/formatting.py
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
class Formatter(ABC):
    """Abstract base class for a reprex formatter. Concrete subclasses should implement the
    formatting logic appropriate to a specific venue for sharing. Call `str(...)` on an instance
    to return the formatted reprex.

    Attributes:
        default_advertise (bool): Whether to render reprexlite advertisement by default
        meta (FormatterMeta): Contains metadata for the formatter, such as label text and an
            example
    """

    default_advertise: ClassVar[bool] = True
    meta: ClassVar[FormatterMetadata]

    @classmethod
    @abstractmethod
    def format(
        cls, reprex_str: str, advertise: Optional[bool] = None, session_info: bool = False
    ) -> str:
        """Format a reprex string for a specific sharing venue.

        Args:
            reprex_str (str): String containing rendered reprex output.
            advertise (Optional[bool], optional): Whether to include the advertisement for
                reprexlite. Defaults to None, which uses a per-formatter default.
            session_info (bool, optional): Whether to include detailed session information.
                Defaults to False.

        Returns:
            str: String containing formatted reprex code. Ends with newline.
        """

Functions

format(reprex_str: str, advertise: Optional[bool] = None, session_info: bool = False) -> str abstractmethod classmethod

Format a reprex string for a specific sharing venue.

Parameters:

Name Type Description Default
reprex_str str

String containing rendered reprex output.

required
advertise Optional[bool]

Whether to include the advertisement for reprexlite. Defaults to None, which uses a per-formatter default.

None
session_info bool

Whether to include detailed session information. Defaults to False.

False

Returns:

Name Type Description
str str

String containing formatted reprex code. Ends with newline.

Source code in reprexlite/formatting.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@classmethod
@abstractmethod
def format(
    cls, reprex_str: str, advertise: Optional[bool] = None, session_info: bool = False
) -> str:
    """Format a reprex string for a specific sharing venue.

    Args:
        reprex_str (str): String containing rendered reprex output.
        advertise (Optional[bool], optional): Whether to include the advertisement for
            reprexlite. Defaults to None, which uses a per-formatter default.
        session_info (bool, optional): Whether to include detailed session information.
            Defaults to False.

    Returns:
        str: String containing formatted reprex code. Ends with newline.
    """

GitHubFormatter

Bases: Formatter

Formatter for rendering reprexes in GitHub Flavored Markdown.

Source code in reprexlite/formatting.py
 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
@register_formatter(venue="ds", label="Discourse (alias for 'gh')")
@register_formatter(venue="so", label="StackOverflow (alias for 'gh')")
@register_formatter(venue="gh", label="Github Flavored Markdown")
class GitHubFormatter(Formatter):
    """Formatter for rendering reprexes in GitHub Flavored Markdown."""

    default_advertise = True
    meta = FormatterMetadata(
        example=dedent(
            """\
            ```python
            2+2
            #> 4
            ```
            """
        )
    )

    @classmethod
    def format(
        cls, reprex_str: str, advertise: Optional[bool] = None, session_info: bool = False
    ) -> str:
        if advertise is None:
            advertise = cls.default_advertise
        out = []
        out.append("```python")
        out.append(reprex_str)
        out.append("```")
        if advertise:
            out.append("\n" + Advertisement().markdown())
        if session_info:
            out.append("\n<details><summary>Session Info</summary>")
            out.append("```text")
            out.append(str(SessionInfo()))
            out.append("```")
            out.append("</details>")
        return "\n".join(out) + "\n"

HtmlFormatter

Bases: Formatter

Formatter for rendering reprexes in HTML. If optional dependency Pygments is available, the rendered HTML will have syntax highlighting for the Python code.

Source code in reprexlite/formatting.py
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
@register_formatter(venue="html", label="HTML")
class HtmlFormatter(Formatter):
    """Formatter for rendering reprexes in HTML. If optional dependency Pygments is
    available, the rendered HTML will have syntax highlighting for the Python code."""

    default_advertise = True
    meta = FormatterMetadata(
        example=dedent(
            """\
            <pre><code>2+2
            #> 4</code></pre>
            """
        )
    )

    @classmethod
    def format(
        cls, reprex_str: str, advertise: Optional[bool] = None, session_info: bool = False
    ) -> str:
        if advertise is None:
            advertise = cls.default_advertise
        out = []
        try:
            from pygments import highlight
            from pygments.formatters import HtmlFormatter
            from pygments.lexers import PythonLexer

            formatter = HtmlFormatter(
                style="friendly", lineanchors=True, linenos=True, wrapcode=True
            )
            out.append(f"<style>{formatter.get_style_defs('.highlight')}</style>")
            out.append(highlight(str(reprex_str), PythonLexer(), formatter))
        except ImportError:
            out.append(f"<pre><code>{reprex_str}</code></pre>")

        if advertise:
            out.append(Advertisement().html().strip())
        if session_info:
            out.append("<details><summary>Session Info</summary>")
            out.append(f"<pre><code>{SessionInfo()}</code></pre>")
            out.append("</details>")
        return "\n".join(out) + "\n"

PyScriptFormatter

Bases: Formatter

Formatter for rendering reprexes as a Python script.

Source code in reprexlite/formatting.py
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
@register_formatter(venue="py", label="Python script")
class PyScriptFormatter(Formatter):
    """Formatter for rendering reprexes as a Python script."""

    default_advertise = False
    meta = FormatterMetadata(
        example=dedent(
            """\
            2+2
            #> 4
            """
        )
    )

    @classmethod
    def format(
        cls, reprex_str: str, advertise: Optional[bool] = None, session_info: bool = False
    ) -> str:
        if advertise is None:
            advertise = cls.default_advertise
        out = [str(reprex_str)]
        if advertise:
            out.append("\n" + Advertisement().code_comment())
        if session_info:
            out.append("")
            sess_lines = str(SessionInfo()).split("\n")
            out.extend("# " + line for line in sess_lines)
        return "\n".join(out) + "\n"

RtfFormatter

Bases: Formatter

Formatter for rendering reprexes in Rich Text Format.

Source code in reprexlite/formatting.py
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
@register_formatter(venue="rtf", label="Rich Text Format")
class RtfFormatter(Formatter):
    """Formatter for rendering reprexes in Rich Text Format."""

    default_advertise = False
    meta = FormatterMetadata(example=None)

    @classmethod
    def format(
        cls, reprex_str: str, advertise: Optional[bool] = None, session_info: bool = False
    ) -> str:
        if advertise is None:
            advertise = cls.default_advertise
        try:
            from pygments import highlight
            from pygments.formatters import RtfFormatter
            from pygments.lexers import PythonLexer
        except ModuleNotFoundError as e:
            if e.name == "pygments":
                raise PygmentsNotFoundError(
                    "Pygments is required for RTF output.", name="pygments"
                )
            else:
                raise

        out = str(reprex_str)
        if advertise:
            out += "\n\n" + Advertisement().text()
        if session_info:
            out += "\n\n" + str(SessionInfo())
        return highlight(out, PythonLexer(), RtfFormatter()) + "\n"

SlackFormatter

Bases: Formatter

Formatter for rendering reprexes as Slack markup.

Source code in reprexlite/formatting.py
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
@register_formatter(venue="slack", label="Slack")
class SlackFormatter(Formatter):
    """Formatter for rendering reprexes as Slack markup."""

    default_advertise = False
    meta = FormatterMetadata(
        example=dedent(
            """\
            ```
            2+2
            #> 4
            ```
            """
        )
    )

    @classmethod
    def format(
        cls, reprex_str: str, advertise: Optional[bool] = None, session_info: bool = False
    ) -> str:
        if advertise is None:
            advertise = cls.default_advertise
        out = []
        out.append("```")
        out.append(str(reprex_str))
        out.append("```")
        if advertise:
            out.append("\n" + Advertisement().text())
        if session_info:
            out.append("\n```")
            out.append(str(SessionInfo()))
            out.append("```")
        return "\n".join(out) + "\n"

Functions

register_formatter(venue: str, label: str)

Decorator that registers a formatter implementation.

Parameters:

Name Type Description Default
venue str

Venue keyword that formatter will be registered to.

required
label str

Short human-readable label explaining the venue.

required
Source code in reprexlite/formatting.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def register_formatter(venue: str, label: str):
    """Decorator that registers a formatter implementation.

    Args:
        venue (str): Venue keyword that formatter will be registered to.
        label (str): Short human-readable label explaining the venue.
    """

    def registrar(cls):
        global formatter_registry
        if not isinstance(cls, type) or not issubclass(cls, Formatter):
            raise NotAFormatterError("Only subclasses of Formatter can be registered.")
        formatter_registry[venue] = cls
        cls.meta.venues[venue] = label
        return cls

    return registrar