Skip to main content

Sphinx Extension - Directives to auto-evaluate Python code-blocks

Project description

PyPI PyPI - Status PyPI - Python Version GitHub License GitHub Workflow Status

sphinxcontrib-repl is an extension to Sphinx document generator tool. The extension introduces repl and repl-quiet directives to run Python REPL interpreters during Sphinx builds the documentation. The content of the directives will be automatically evaluated line-by-line in the interpreter, and repl blocks will add what would be printed on the interpreter to the output document.

Contents

Installation

Install from PyPI:

pip install sphinxcontrib-repl

Then, inside your Sphinx conf.py, add sphinxcontrib.repl to your list of extensions:

extensions = [
    "sphinxcontrib.repl",
    # other extensions...
]

Basic Usage

To run Python code in the interpreter, list the code in a repl block:

.. repl::

   2*3+4
   x=5
   f"{x=}"

First of such block will invoke a dedicated Python interpreter process, which will continue to run in the background for each RST document until the document is fully parsed. The above block of code will produce the following document block:

>>> 2*3+4
10
>>> x=5
>>> f"{x=}"
'x=5'

As the interpreter process will run continuously, the variables will carry between blocks. For example, after the above repl block, the variable x may be used in any subsequent repl blocks (unless you delete it):

.. repl::

   x+4

will produce:

>>> x+4
9

A REPL block may contain (potentially nested) condition/loop statements:

.. repl::

   for i in range(5):
       if i>2:
           i+1

outputs

>>> for i in range(5):
...     if i>2:
...         i+1
...
4
5

Note that a trailing empty line to terminate the indented block will be inserted automatically.

To hide nuisance operations (e.g., importing common libraries), use repl-quiet block:

.. repl-quiet::

   import numpy as np

After this block, the Numpy package is loaded onto the interpreter, but the import line will not be printed in the document.

Matplotlib Integration

Plotting matplotlib figures in the REPL interpreter process yields the figures to be automatically exported to the document:

.. repl::

   import numpy as np
   from matplotlib import pyplot as plt

   plt.plot(np.random.randn(100))
   plt.figure()
   plt.plot(np.random.randn(100))
   plt.show()

The above RST repl block generates the following Python code snippet and the figure images:

>>> import numpy as np
>>> from matplotlib import pyplot as plt
>>> plt.plot(np.random.randn(100))
[<matplotlib.lines.Line2D object at 0x0000025C046CCDF0>]
>>> plt.figure()
<Figure size 800x400 with 0 Axes>
>>> plt.plot(np.random.randn(100))
[<matplotlib.lines.Line2D object at 0x0000025C0471A7F0>]
>>> plt.show()
docs/imgs/mpl_0_1.svg docs/imgs/mpl_0_2.svg

To hide the Python code, use the repl-quiet directive, which will only display the figures:

.. repl-quiet::

   plt.plot(np.random.randn(100))
   plt.title('plotted in repl-quiet')
   plt.show()

This code prints only the image:

docs/imgs/mpl_1_1.svg

Options

Visibility Control Options

By default, repl directive shows everything and repl-quiet hides everything. It is possible to control the visibility of input and output lines in the repl directive with the following directive options and magic comments.

Directive

Magic comment

Description

:hide-input:

#repl:hide-input

Hide input (directive option value: true or false)

:hide-output:

#repl:hide-output

Hide output (directive option value: true or false)

#repl:show-input

Show input

#repl:show-output

Show output

#repl:hide

Hide both input and output

#repl:show

Show both input and output

For example,

.. repl::
   :hide-output: true

   'only shown as input'

outputs

>>> 'only shown as input'

and does not show the echoed output string.

To provide a fine-grain control, there are 6 magic comments to switch the visibility. They can be applied only to a line (as an inline comment) or toggle for the remainder of the directive context.

.. repl::

   #repl:hide-input
   'no input'
   'show input' #repl:show
   'no input again'
   #repl:show-input

   #repl:hide-output
   'no output'
   'show output' #repl:show
   'no output again'
   #repl:show-output

outputs

'no input'
>>> 'show input'
'show input'
'no input again'
>>>
>>> 'no output'
>>> 'show output'
'show output'
>>> 'no output again'

Matplotlib Options

The Matplotlib figure properties can be customized by specifying the following options either as the extension options (in the Sphinx conf.py file) or as the directive options. Be aware that the directive options persist in the subsequent directives.

In addition to the figure options, any Matplotlib rc settings could be changed via rc_params option. Consult the default matplotlibrc file for possible entries. The exposed options are of the savefig group, except for figsize which sets figure.figsize option in the REPL interpreter.

Extension

Directive

Default

Description

repl_mpl_disable

False

True to disable matplotlib support

repl_mpl_dpi

96

raster dots per inch

repl_mpl_format

svg

output image format (default is pdf for latex) {png, ps, pdf, svg}

repl_mpl_figsize

:mpl-figsize:

6.4, 4.8

figure size in inches

repl_mpl_facecolor

:mpl-facecolor:

white

figure face color

repl_mpl_edgecolor

:mpl-edgecolor:

white

figure edge color

repl_mpl_bbox

:mpl-bbox:

standard

bounding box {tight, standard}

repl_mpl_pad_inches

:mpl-pad-inches:

0.1

padding to be used, when bbox is set to tight

repl_mpl_transparent

:mpl-transparent:

False

whether figures are saved with a transparent

repl_mpl_rc_params

:mpl-rc-params:

other rcParams options

Example of extension options in conf.py:

repl_mpl_disable = False
repl_mpl_figsize = (8, 4)
repl_mpl_dpi = 96
repl_mpl_format = "svg"
repl_mpl_facecolor = "gray"
repl_mpl_edgecolor = "black"
repl_mpl_bbox = "tight"
repl_mpl_pad_inches = 0.1
repl_mpl_transparent = False
repl_mpl_rc_params = {"lines.marker": "o"}

Example of directive options:

.. repl-quiet::
   :mpl-figsize: 6, 4
   :mpl-facecolor: orange
   :mpl-edgecolor: red
   :mpl-bbox: standard
   :mpl-pad-inches:  0.1
   :mpl-transparent:  False
   :mpl-rc-params:  {"lines.marker": "x", "lines.markersize": 3}

   plt.plot(np.random.randn(100))
   plt.title('plotted in repl-quiet')
   plt.show()

Image Options

All of the options of the image directive, except for target (since target image is generated by the REPL process). Currently, these options applies to the Matplotlib figure images.

Directive

Description

:image-alt:

Alternate text: a short description of the image

:image-height:

The desired height of the image

:image-width:

The width of the image

:image-scale:

The uniform scaling factor of the image

:image-align:

The alignment of the image

:image-class:

Set a “classes” attribute value on the doctree element generated by the directive

Table Options

By specifying :table-ncols: directive option to a positive integer, the Matplotlib figures will be shown in a table with as many columns.

Directive

Description

:table-ncols:

Number of columns (if 0 or omitted, no table will be used)

:table-align:

The horizontal alignment of the table {left, center, or right}

:table-width:

Sets the width of the table to the specified length or percentage of the line width

:table-widths:

Explicitly set column widths. Specifies relative widths if used with the width option.

{auto, grid, or a list of integers}

:table-class:

Set a “classes” attribute value on the doctree element generated by the directive

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sphinxcontrib-repl-0.4.1.tar.gz (20.8 kB view details)

Uploaded Source

Built Distribution

sphinxcontrib_repl-0.4.1-py3-none-any.whl (17.8 kB view details)

Uploaded Python 3

File details

Details for the file sphinxcontrib-repl-0.4.1.tar.gz.

File metadata

  • Download URL: sphinxcontrib-repl-0.4.1.tar.gz
  • Upload date:
  • Size: 20.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.9.15

File hashes

Hashes for sphinxcontrib-repl-0.4.1.tar.gz
Algorithm Hash digest
SHA256 9120d0b7a762798c3ea0fc8304e852a91a4301c1d460b56139122fcd78a3b4d9
MD5 0737b3a91ef69356b6f7630d31872243
BLAKE2b-256 15a5620853f853c344ddcb1964423a80abf467c0d26bab46bac89f8b6bcafc30

See more details on using hashes here.

File details

Details for the file sphinxcontrib_repl-0.4.1-py3-none-any.whl.

File metadata

File hashes

Hashes for sphinxcontrib_repl-0.4.1-py3-none-any.whl
Algorithm Hash digest
SHA256 6893c21acb2c168d207a86baabccafd762f9f3b8346aec4bb8931768564be524
MD5 c17a270731925a022a683e9299490e66
BLAKE2b-256 658fc7e0c56aecbf4b7f088ad4f2063fc02b5fece656ba6e864a6944d8991df8

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page