Skip to content

reprexlite.formatting

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
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
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
254
255
256
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
247
248
249
250
251
252
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
243
244
245
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
258
259
260
def text(self) -> str:
    """Render reprexlite advertisement in plain text."""
    return f"Created at {self.timestamp} by {self.pkg} {self.version} <{self.url}>"

FormatterRegistry

Registry of formatters keyed by venue keywords.

Source code in reprexlite/formatting.py
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
class FormatterRegistry:
    """Registry of formatters keyed by venue keywords."""

    _registry: Dict[str, FormatterRegistration] = {}

    def __getitem__(self, key: Venue) -> FormatterRegistration:
        return self._registry[Venue(key)]

    def __contains__(self, key: Venue) -> bool:
        return Venue(key) in self._registry

    def items(self):
        return self._registry.items()

    def keys(self):
        return self._registry.keys()

    def values(self):
        return self._registry.values()

    def register(self, venue: Venue, 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 _register(fn: Formatter):
            self._registry[Venue(venue)] = FormatterRegistration(fn=fn, label=label)
            return fn

        return _register

Functions

register(venue: Venue, 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
41
42
43
44
45
46
47
48
49
50
51
52
53
def register(self, venue: Venue, 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 _register(fn: Formatter):
        self._registry[Venue(venue)] = FormatterRegistration(fn=fn, label=label)
        return fn

    return _register

Functions

format_as_html(reprex_str: str, config: Optional[ReprexConfig] = None) -> str

Format a rendered reprex reprex as an HTML code block. If optional dependency Pygments is available, the rendered HTML will have syntax highlighting for the Python code. By default, includes a footer that credits reprexlite.

Parameters:

Name Type Description Default
reprex_str str

The reprex string to render.

required
config Optional[ReprexConfig]

Configuration for the reprex. Defaults to None.

None

Returns:

Name Type Description
str str

The rendered reprex

Example
2+2
#> 4
Source code in reprexlite/formatting.py
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
@formatter_registry.register(venue=Venue.HTML, label="HTML")
def format_as_html(reprex_str: str, config: Optional[ReprexConfig] = None) -> str:
    """Format a rendered reprex reprex as an HTML code block. If optional dependency Pygments is
    available, the rendered HTML will have syntax highlighting for the Python code. By default,
    includes a footer that credits reprexlite.

    Args:
        reprex_str (str): The reprex string to render.
        config (Optional[ReprexConfig]): Configuration for the reprex. Defaults to None.

    Returns:
        str: The rendered reprex

    Example:
        <pre><code>2+2
        #> 4</code></pre>
    """
    if config is None:
        config = ReprexConfig()
    advertise = config.advertise if config.advertise is not None else True
    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 config.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"

format_as_markdown(reprex_str: str, config: Optional[ReprexConfig] = None) -> str

Format a rendered reprex reprex as a GitHub-Flavored Markdown code block. By default, includes a footer that credits reprexlite.

Parameters:

Name Type Description Default
reprex_str str

The reprex string to render.

required
config Optional[ReprexConfig]

Configuration for the reprex. Defaults to None.

None

Returns:

Name Type Description
str str

The rendered reprex

Example
2+2
#> 4
Source code in reprexlite/formatting.py
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
@formatter_registry.register(venue=Venue.DS, label=f"Discourse (alias for '{Venue.GH.value}')")
@formatter_registry.register(venue=Venue.SO, label=f"StackOverflow (alias for '{Venue.GH.value}')")
@formatter_registry.register(venue=Venue.GH, label="Github Flavored Markdown")
def format_as_markdown(
    reprex_str: str,
    config: Optional[ReprexConfig] = None,
) -> str:
    """
    Format a rendered reprex reprex as a GitHub-Flavored Markdown code block. By default, includes
    a footer that credits reprexlite.

    Args:
        reprex_str (str): The reprex string to render.
        config (Optional[ReprexConfig]): Configuration for the reprex. Defaults to None.

    Returns:
        str: The rendered reprex

    Example:
        ```python
        2+2
        #> 4
        ```
    """
    if config is None:
        config = ReprexConfig()
    advertise = config.advertise if config.advertise is not None else True
    out = []
    out.append("```python")
    out.append(reprex_str)
    out.append("```")
    if advertise:
        out.append("\n" + Advertisement().markdown())
    if config.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"

format_as_python_script(reprex_str: str, config: Optional[ReprexConfig] = None) -> str

Format a rendered reprex reprex as a Python script.

Parameters:

Name Type Description Default
reprex_str str

The reprex string to render.

required
config Optional[ReprexConfig]

Configuration for the reprex. Defaults to None.

None

Returns:

Name Type Description
str str

The rendered reprex

Example

2+2

> 4

Source code in reprexlite/formatting.py
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
@formatter_registry.register(venue=Venue.PY, label="Python script")
def format_as_python_script(reprex_str: str, config: Optional[ReprexConfig] = None) -> str:
    """Format a rendered reprex reprex as a Python script.

    Args:
        reprex_str (str): The reprex string to render.
        config (Optional[ReprexConfig]): Configuration for the reprex. Defaults to None.

    Returns:
        str: The rendered reprex

    Example:
        2+2
        #> 4
    """
    if config is None:
        config = ReprexConfig()
    advertise = config.advertise if config.advertise is not None else False
    out = [str(reprex_str)]
    if advertise:
        out.append("\n" + Advertisement().code_comment())
    if config.session_info:
        out.append("")
        sess_lines = str(SessionInfo()).split("\n")
        out.extend("# " + line for line in sess_lines)
    return "\n".join(out) + "\n"

format_as_rtf(reprex_str: str, config: Optional[ReprexConfig] = None) -> str

Format a rendered reprex reprex as a Rich Text Format (RTF) document. Requires dependency Pygments.

Source code in reprexlite/formatting.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
@formatter_registry.register(venue=Venue.RTF, label="Rich Text Format")
def format_as_rtf(reprex_str: str, config: Optional[ReprexConfig] = None) -> str:
    """Format a rendered reprex reprex as a Rich Text Format (RTF) document. Requires dependency
    Pygments."""
    if config is None:
        config = ReprexConfig()
    advertise = config.advertise if config.advertise is not None else False
    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 config.session_info:
        out += "\n\n" + str(SessionInfo())
    return highlight(out, PythonLexer(), RtfFormatter()) + "\n"

format_for_slack(reprex_str: str, config: Optional[ReprexConfig] = None) -> str

Format a rendered reprex as Slack markup.

Parameters:

Name Type Description Default
reprex_str str

The reprex string to render.

required
config Optional[ReprexConfig]

Configuration for the reprex. Defaults to None.

None

Returns:

Name Type Description
str str

The rendered reprex

Example
2+2
#> 4
Source code in reprexlite/formatting.py
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
@formatter_registry.register(venue=Venue.SLACK, label="Slack")
def format_for_slack(reprex_str: str, config: Optional[ReprexConfig] = None) -> str:
    """Format a rendered reprex as Slack markup.

    Args:
        reprex_str (str): The reprex string to render.
        config (Optional[ReprexConfig]): Configuration for the reprex. Defaults to None.

    Returns:
        str: The rendered reprex

    Example:
        ```
        2+2
        #> 4
        ```
    """
    if config is None:
        config = ReprexConfig()
    advertise = config.advertise if config.advertise is not None else False
    out = []
    out.append("```")
    out.append(str(reprex_str))
    out.append("```")
    if advertise:
        out.append("\n" + Advertisement().text())
    if config.session_info:
        out.append("\n```")
        out.append(str(SessionInfo()))
        out.append("```")
    return "\n".join(out) + "\n"