literalinclude: Including Part of a File

🌐 AI Reader Read this document in English or ask questions: Open in Claude, ChatGPT, or Gemini ↗

In MyST, literalinclude is a ```{literalinclude} <path> fence with the same options as in reST. A path is relative to the current document; a path starting with / is relative to the Sphinx source folder.

Every example below includes example.py from this folder.

By function or class name (no markers needed)

:pyobject: finds a function, class or method by name, so the include survives any edit of the file:

```{literalinclude} example.py
:pyobject: Store.put
:emphasize-lines: 4
```
    def put(self, value: str) -> str:
        # --- begin: put-body
        key = make_id()
        self.data[key] = value
        return key

A file elsewhere in the repository

The path can point outside docs/source, for example straight at this repository’s Python source:

```{literalinclude} ../../../../cookiecutter_pywf_kb_site_demo/doc_id.py
:pyobject: is_valid_doc_id
```
def is_valid_doc_id(doc_id: T.Any) -> bool:
    """
    Return True if ``doc_id`` is a string matching :data:`DOC_ID_PATTERN`.
    """
    return isinstance(doc_id, str) and bool(DOC_ID_PATTERN.match(doc_id))

Option cheat sheet

Option

Effect

:start-after: / :end-before:

From after a line / up to before a line (marker lines excluded)

:start-at: / :end-at:

From a line / up to a line (marker lines included)

:pyobject:

A Python function / class / method by name

:lines:

By line numbers, such as 1,3,5-10. Shifts with every edit: avoid

:dedent:

Remove the common indentation

:emphasize-lines:

Highlight lines (numbers relative to the included snippet)

:caption: / :linenos:

Caption / line numbers

Note

PyCharm and GitHub Markdown previews show {literalinclude} as a code block with the directive text; only the Sphinx build shows the included code.