literalinclude: Including Part of a File¶
🌐 AI ReaderRead 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.
Region markers in comments (recommended)¶
Mark a region of the Python file with a pair of comments:
# --- begin: make-id
def make_id(n: int = 12) -> str: ...
# --- end: make-id
Then :start-after: and :end-before: include only what is between them; the marker lines themselves stay out:
```{literalinclude} example.py
:language: python
:start-after: "# --- begin: make-id"
:end-before: "# --- end: make-id"
```
Result:
def make_id(n: int = 12) -> str:
alphabet = string.ascii_letters
return "".join(secrets.choice(alphabet) for _ in range(n))
A region inside a method, dedented¶
For a region inside a method, :dedent: removes the common indentation; add a caption and line numbers:
```{literalinclude} example.py
:language: python
:start-after: "# --- begin: put-body"
:end-before: "# --- end: put-body"
:dedent:
:caption: Body of Store.put
:linenos:
```
1key = make_id()
2self.data[key] = value
3return key
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 |
|---|---|
|
From after a line / up to before a line (marker lines excluded) |
|
From a line / up to a line (marker lines included) |
|
A Python function / class / method by name |
|
By line numbers, such as |
|
Remove the common indentation |
|
Highlight lines (numbers relative to the included snippet) |
|
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.