Skip to content

reprexlite.formatting

Attributes

Venue = Enum('Venue', names={v.upper(): vfor v in venues_dispatcher.keys()}, type=str) module-attribute

venues_dispatcher = {'gh': GitHubReprex, 'so': GitHubReprex, 'ds': GitHubReprex, 'html': HtmlReprex, 'py': PyScriptReprex, 'rtf': RtfReprex, 'slack': SlackReprex} module-attribute

Mapping from venue keywords to their Reprex implementation.

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
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
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:%S %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}>"

Attributes

pkg = 'reprexlite' class-attribute instance-attribute
timestamp = datetime.now().astimezone().strftime('%Y-%m-%d %H:%M:%S %Z') instance-attribute
url = 'https://github.com/jayqi/reprexlite' class-attribute instance-attribute
version = f'v{__version__}' instance-attribute

Functions

__init__()
Source code in reprexlite/formatting.py
171
172
173
def __init__(self):
    self.timestamp = datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S %Z")
    self.version = f"v{__version__}"
code_comment()

Render reprexlite advertisement as a comment in Python code.

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

Render reprexlite advertisement in HTML.

Source code in reprexlite/formatting.py
179
180
181
182
183
184
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()

Render reprexlite advertisement in GitHub Flavored Markdown.

Source code in reprexlite/formatting.py
175
176
177
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()

Render reprexlite advertisement in plain text.

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

GitHubReprex

Bases: Reprex

Concrete implementation for rendering reprexes in GitHub Flavored Markdown.

Source code in reprexlite/formatting.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class GitHubReprex(Reprex):
    """Concrete implementation for rendering reprexes in GitHub Flavored Markdown."""

    default_advertise: bool = True

    def __str__(self) -> str:
        out = []
        out.append("```python")
        out.append(str(self.code_block))
        out.append("```")
        if self.advertise:
            out.append("\n" + Advertisement().markdown())
        if self.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)

Attributes

advertise = self.default_advertise if advertise is None else advertise instance-attribute
code_block = code_block instance-attribute
default_advertise = True class-attribute instance-attribute
session_info = session_info instance-attribute

Functions

__init__(code_block, advertise=None, session_info=False)
Source code in reprexlite/formatting.py
25
26
27
28
29
30
def __init__(
    self, code_block: CodeBlock, advertise: Optional[bool] = None, session_info: bool = False
):
    self.code_block: CodeBlock = code_block
    self.advertise: bool = self.default_advertise if advertise is None else advertise
    self.session_info: bool = session_info

HtmlReprex

Bases: Reprex

Concrete implementation 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
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
class HtmlReprex(Reprex):
    """Concrete implementation for rendering reprexes in HTML. If optional dependency Pygments is
    available, the rendered HTML will have syntax highlighting for the Python code."""

    default_advertise: bool = True

    def __str__(self) -> str:
        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(self.code_block), PythonLexer(), formatter))
        except ImportError:
            out.append(f"<pre><code>{self.code_block}</code></pre>")

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

Attributes

advertise = self.default_advertise if advertise is None else advertise instance-attribute
code_block = code_block instance-attribute
default_advertise = True class-attribute instance-attribute
session_info = session_info instance-attribute

Functions

__init__(code_block, advertise=None, session_info=False)
Source code in reprexlite/formatting.py
25
26
27
28
29
30
def __init__(
    self, code_block: CodeBlock, advertise: Optional[bool] = None, session_info: bool = False
):
    self.code_block: CodeBlock = code_block
    self.advertise: bool = self.default_advertise if advertise is None else advertise
    self.session_info: bool = session_info

PyScriptReprex

Bases: Reprex

Concrete implementation for rendering reprexes as a Python script.

Source code in reprexlite/formatting.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
class PyScriptReprex(Reprex):
    """Concrete implementation for rendering reprexes as a Python script."""

    default_advertise: bool = False

    def __str__(self) -> str:
        out = [str(self.code_block)]
        if self.advertise:
            out.append("\n" + Advertisement().code_comment())
        if self.session_info:
            out.append("")
            sess_lines = str(SessionInfo()).split("\n")
            out.extend("# " + line for line in sess_lines)
        return "\n".join(out)

Attributes

advertise = self.default_advertise if advertise is None else advertise instance-attribute
code_block = code_block instance-attribute
default_advertise = False class-attribute instance-attribute
session_info = session_info instance-attribute

Functions

__init__(code_block, advertise=None, session_info=False)
Source code in reprexlite/formatting.py
25
26
27
28
29
30
def __init__(
    self, code_block: CodeBlock, advertise: Optional[bool] = None, session_info: bool = False
):
    self.code_block: CodeBlock = code_block
    self.advertise: bool = self.default_advertise if advertise is None else advertise
    self.session_info: bool = session_info

Reprex

Bases: ABC

Abstract base class for a reprex instance. 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
code_block CodeBlock

instance of CodeBlock

advertise bool

whether to render reprexlite advertisement

session_info bool

whether to render session info

Source code in reprexlite/formatting.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Reprex(ABC):
    """Abstract base class for a reprex instance. 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:
        code_block (CodeBlock): instance of [`CodeBlock`][reprexlite.code.CodeBlock]
        advertise (bool): whether to render reprexlite advertisement
        session_info (bool): whether to render session info
    """

    default_advertise: bool
    """Default for whether to include reprexlite advertisement for this venue format."""

    def __init__(
        self, code_block: CodeBlock, advertise: Optional[bool] = None, session_info: bool = False
    ):
        self.code_block: CodeBlock = code_block
        self.advertise: bool = self.default_advertise if advertise is None else advertise
        self.session_info: bool = session_info

    @abstractmethod
    def __str__(self) -> str:  # pragma: no cover
        pass

Attributes

advertise = self.default_advertise if advertise is None else advertise instance-attribute
code_block = code_block instance-attribute
default_advertise instance-attribute

Default for whether to include reprexlite advertisement for this venue format.

session_info = session_info instance-attribute

Functions

__init__(code_block, advertise=None, session_info=False)
Source code in reprexlite/formatting.py
25
26
27
28
29
30
def __init__(
    self, code_block: CodeBlock, advertise: Optional[bool] = None, session_info: bool = False
):
    self.code_block: CodeBlock = code_block
    self.advertise: bool = self.default_advertise if advertise is None else advertise
    self.session_info: bool = session_info

RtfReprex

Bases: Reprex

Concrete implementation for rendering reprexes in Rich Text Format.

Source code in reprexlite/formatting.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
class RtfReprex(Reprex):
    """Concrete implementation for rendering reprexes in Rich Text Format."""

    default_advertise: bool = False

    def __str__(self) -> str:
        try:
            from pygments import highlight
            from pygments.formatters import RtfFormatter
            from pygments.lexers import PythonLexer
        except ImportError:
            raise ImportError("Pygments is required for RTF output.")

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

Attributes

advertise = self.default_advertise if advertise is None else advertise instance-attribute
code_block = code_block instance-attribute
default_advertise = False class-attribute instance-attribute
session_info = session_info instance-attribute

Functions

__init__(code_block, advertise=None, session_info=False)
Source code in reprexlite/formatting.py
25
26
27
28
29
30
def __init__(
    self, code_block: CodeBlock, advertise: Optional[bool] = None, session_info: bool = False
):
    self.code_block: CodeBlock = code_block
    self.advertise: bool = self.default_advertise if advertise is None else advertise
    self.session_info: bool = session_info

SlackReprex

Bases: Reprex

Concrete implementation for rendering reprexes as Slack markup.

Source code in reprexlite/formatting.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
class SlackReprex(Reprex):
    """Concrete implementation for rendering reprexes as Slack markup."""

    default_advertise: bool = False

    def __str__(self):
        out = []
        out.append("```")
        out.append(str(self.code_block))
        out.append("```")
        if self.advertise:
            out.append("\n" + Advertisement().text())
        if self.session_info:
            out.append("\n```")
            out.append(str(SessionInfo()))
            out.append("```")
        return "\n".join(out)

Attributes

advertise = self.default_advertise if advertise is None else advertise instance-attribute
code_block = code_block instance-attribute
default_advertise = False class-attribute instance-attribute
session_info = session_info instance-attribute

Functions

__init__(code_block, advertise=None, session_info=False)
Source code in reprexlite/formatting.py
25
26
27
28
29
30
def __init__(
    self, code_block: CodeBlock, advertise: Optional[bool] = None, session_info: bool = False
):
    self.code_block: CodeBlock = code_block
    self.advertise: bool = self.default_advertise if advertise is None else advertise
    self.session_info: bool = session_info