Code blocks¶
Code blocks can be easily represented with the code-block directive.
Together with Pygments, Sphinx will automatically
highlight the syntax. You can specify the appropriate language for a code block
with
- .. code-block:: LANGUAGE¶
You can use this for example like this:
.. code-block:: python import this
Optionen
- :linenos:¶
For
code-block, thelinenosoption can also be used to specify that the code block should be displayed with line numbers:.. code-block:: python :linenos: import this
1import this
- :lineno-start:¶
Die erste Zeilennummer kann mit der
lineno-start-Option ausgewählt werden;linenoswird dann automatisch aktiviert: The first line number can be selected with thelineno-startoption;linenoswill then be activated automatically:.. code-block:: python :lineno-start: 10 import antigravity
10import antigravity
- :emphasize-lines:¶
emphasize-linesallows you to emphasise individual lines.
- .. literalinclude:: FILENAME¶
allows you to include external files.
Options
- :emphasize-lines:¶
- :linenos:¶
Here is an example from our Jupyter Tutorial:
.. literalinclude:: main.py :emphasize-lines: 4, 9-12, 20-22 :linenos:
1from typing import Optional 2 3from fastapi import FastAPI 4from pydantic import BaseModel 5 6app = FastAPI() 7 8 9class Task(BaseModel): 10 name: str 11 price: float 12 is_offer: Optional[bool] = None 13 14 15@app.get("/") 16def read_root(): 17 return {"Hello": "World"} 18 19 20@app.get("/cusy.tasks/{task_id}") 21def read_task(task_id: int, q: Optional[str] = None): 22 return {"task_id": task_id, "q": q} 23 24 25@app.put("/cusy.tasks/{task_id}") 26def update_task(task_id: int, task: Task): 27 return {"task_name": task.name, "task_id": task_id}
- :diff:¶
If you want to show the diff of your code, you can specify the old file with the diff option, for example:
.. literalinclude:: main.py :diff: main.py.orig
--- /home/runner/work/python-basics-tutorial/python-basics-tutorial/docs/document/sphinx/main.py.orig +++ /home/runner/work/python-basics-tutorial/python-basics-tutorial/docs/document/sphinx/main.py @@ -1,12 +1,27 @@ from typing import Optional + from fastapi import FastAPI +from pydantic import BaseModel app = FastAPI() + + +class Task(BaseModel): + name: str + price: float + is_offer: Optional[bool] = None + @app.get("/") def read_root(): return {"Hello": "World"} + @app.get("/cusy.tasks/{task_id}") def read_task(task_id: int, q: Optional[str] = None): return {"task_id": task_id, "q": q} + + +@app.put("/cusy.tasks/{task_id}") +def update_task(task_id: int, task: Task): + return {"task_name": task.name, "task_id": task_id}
Obsolete code¶
- .. deprecated:: version¶
Describes when the function became obsolete. An explanation can also be given to inform what should be used instead. For example
.. deprecated:: 4.1 instead use :func:`new_function`.
Deprecated since version 4.1: instead use
new_function().
- :py:module:deprecated:¶
Marks a Python module as obsolete; it is then marked as such in various places.