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
, thelinenos
option 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;linenos
wird dann automatisch aktiviert: The first line number can be selected with thelineno-start
option;linenos
will then be activated automatically:.. code-block:: python :lineno-start: 10 import antigravity
10import antigravity
- :emphasize-lines:¶
emphasize-lines
allows 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 Item(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("/items/{item_id}") 21def read_item(item_id: int, q: Optional[str] = None): 22 return {"item_id": item_id, "q": q} 23 24 25@app.put("/items/{item_id}") 26def update_item(item_id: int, item: Item): 27 return {"item_name": item.name, "item_id": item_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,8 +1,15 @@ from typing import Optional from fastapi import FastAPI +from pydantic import BaseModel app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: Optional[bool] = None @app.get("/") @@ -13,3 +20,8 @@ @app.get("/items/{item_id}") def read_item(item_id: int, q: Optional[str] = None): return {"item_id": item_id, "q": q} + + +@app.put("/items/{item_id}") +def update_item(item_id: int, item: Item): + return {"item_name": item.name, "item_id": item_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.