Add section on Python code preparation

This commit is contained in:
Juan Luis Cano Rodríguez 2021-08-10 10:57:18 +02:00
parent 2c1fa831c1
commit a5c684510e
2 changed files with 73 additions and 0 deletions

View File

@ -111,3 +111,74 @@ And finally, this is how the result would look like:
HTML result of documenting a Python function in Sphinx with cross-references
Beautiful, isn't it?
Including doctests in your documentation
----------------------------------------
Since you are now describing code from a Python library, it will become useful
to keep both the documentation and the code as synchronized as possible.
One of the ways to do that in Sphinx is to include code snippets in the
documentation, called *doctests*, that are executed when the documentation is
built.
To demonstrate doctests and other Sphinx features covered in this tutorial,
you will need to setup some basic Python infrastructure first.
Preparing the Python library
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Begin by activating the virtual environment (as seen in the :ref:`getting
started <tutorial-getting-started>` section of the tutorial) and install
`flit <https://pypi.org/project/flit/>`_ on it:
.. code-block:: console
$ source .venv/bin/activate
(.venv) $ python -m pip install "flit~=3.3"
Next, create two files on the same level as ``README.rst``: ``pyproject.toml``
and ``lumache.py``, with these contents:
.. code-block:: toml
:caption: pyproject.toml
[build-system]
requires = ["flit_core >=3.2,<4"]
build-backend = "flit_core.buildapi"
[project]
name = "lumache"
authors = [{name = "Graziella", email = "graziella@lumache"}]
dynamic = ["version", "description"]
.. code-block:: python
:caption: lumache.py
"""
Lumache - Python library for cooks and food lovers.
"""
__version__ = "0.1.0"
And finally, install your own code and check that importing it works:
.. code-block:: console
(.venv) $ flit install --symlink
...
(.venv) $ python -c 'import lumache; print("OK!")'
OK!
Congratulations! You have created a basic Python library.
.. note::
The ``pyproject.toml`` file you created above is required so that
your library can be installed. On the other hand,
``flit install --symlink`` is an alternative to ``pip install .``
that removes the need to reinstall the library every time you make
a change, which is convenient.
An alternative is to not create ``pyproject.toml`` at all,
and setting the :envvar:`PYTHONPATH`, :py:data:`sys.path`, or
equivalent. However, the ``pyproject.toml`` approach is more robust.

View File

@ -1,6 +1,8 @@
Getting started
===============
.. _tutorial-getting-started:
Setting up your project and development environment
---------------------------------------------------