Examples

Basic REPL

.. py-repl::

Light theme, minimal

.. py-repl::
   :theme: catppuccin-latte
   :no-header:
   :no-banner:

Startup script

The :src: option loads a Python script into the REPL namespace. If the script defines a setup() function, its output is shown when the REPL starts.

Startup script:

message = "Hello from the startup script!"


def setup():
    print(message)
    print("Try: message")

RST content:

.. py-repl::
   :src: _static/setup.py

Rendered result:

Replay session

Inline directive content should follow Doctest-style (>>> / ...) and is used as replay prompts.

.. py-repl::
   :no-header:
   :no-banner:

   >>> x = 2 + 2
   >>> print(f"{x=}")
   >>> x * 10
   >>> class Foo:
   ...     x = 1
   ...
   >>> Foo()

Combine a silent bootstrap file with a visible replay body:

.. py-repl::
   :src: _static/setup.py
   :no-header:

   >>> print(message)

Use :replay: on :src: to source a file as replay.

Source script:

greeting = "Hello from replay mode"
print(greeting)
greeting.upper()

RST content:

.. py-repl::
   :src: _static/replay_demo.py
   :replay:
   :no-header:
   :no-banner:

Rendered result:

Autodoc

The documented module’s source is loaded in advance before replay, so module members are available in the REPL namespace. Modules under the Sphinx source tree use silent :src:; installed packages use packages=.

Source module:

"""Demo module for autodoc doctest REPL integration."""

def example_generator(n):
    """Generators yield values useful for iteration.

    Example:

        >>> print([i for i in example_generator(4)])
        [0, 1, 2, 3]

    """
    yield from range(n)

RST content:

.. autofunction:: autodoc_demo.example_generator

Rendered result:

autodoc_demo.example_generator(n)

Generators yield values useful for iteration.

Example