From 0983f9cea1b6b4ae93b2ccb18d09b4456948d57e Mon Sep 17 00:00:00 2001 From: veit Date: Wed, 30 Sep 2026 17:03:13 +0200 Subject: [PATCH 1/8] :memo: Update test section * Add tdd for legacy software and SOLID principles --- docs/appendix/glossary.rst | 16 +- docs/document/sphinx/test.rst | 8 +- docs/libs/batteries.rst | 2 +- docs/test/index.rst | 9 +- docs/test/{ => libs}/github-actions-run.png | Bin docs/test/{ => libs}/github-actions.png | Bin docs/test/{ => libs}/hypothesis.rst | 6 +- docs/test/libs/index.rst | 32 ++ docs/test/{ => libs}/mock/assert_called.rst | 0 docs/test/{ => libs}/mock/autospec.rst | 0 docs/test/{ => libs}/mock/examples.rst | 6 +- docs/test/{ => libs}/mock/index.rst | 0 docs/test/{ => libs}/mock/limitations.rst | 0 docs/test/{ => libs}/mock/plugins.rst | 0 docs/test/{ => libs}/mock/spies.rst | 0 docs/test/{ => libs}/mock/test_mock.py | 0 docs/test/{ => libs}/pytest/api.png | Bin .../{ => libs}/pytest/builtin-fixtures.rst | 2 +- docs/test/{ => libs}/pytest/ci.yaml | 0 .../pytest/command-line-options.rst | 0 docs/test/{ => libs}/pytest/config.rst | 0 docs/test/{ => libs}/pytest/coverage.png | Bin docs/test/{ => libs}/pytest/coverage.rst | 0 docs/test/{ => libs}/pytest/debug.rst | 0 docs/test/{ => libs}/pytest/examples.rst | 0 docs/test/{ => libs}/pytest/fixtures.rst | 0 docs/test/{ => libs}/pytest/functions.rst | 0 docs/test/{ => libs}/pytest/index.rst | 6 +- docs/test/{ => libs}/pytest/markers.rst | 0 docs/test/{ => libs}/pytest/missing.png | Bin docs/test/{ => libs}/pytest/params.rst | 0 docs/test/{ => libs}/pytest/plugins.rst | 0 docs/test/{ => libs}/pytest/test_one.py | 0 docs/test/{ => libs}/pytest/test_pytest.py | 0 docs/test/{ => libs}/pytest/test_two.py | 0 docs/test/{ => libs}/pytest/testsuite.rst | 3 +- docs/test/{ => libs}/test_arithmetic.py | 0 docs/test/{ => libs}/test_emails.py | 0 docs/test/{ => libs}/test_emails_2.py | 0 docs/test/{ => libs}/test_hypothesis.py | 0 docs/test/{ => libs}/test_mock.py | 0 docs/test/{ => libs}/test_pytest.py | 0 docs/test/{ => libs}/tox.rst | 2 +- docs/test/{ => libs}/unittest.rst | 30 +- docs/test/{ => methods}/bdd.rst | 0 docs/test/methods/forms.py | 55 ++++ docs/test/methods/index.rst | 16 + docs/test/methods/legacy.rst | 307 ++++++++++++++++++ docs/test/methods/solid.rst | 208 ++++++++++++ docs/test/{ => methods}/tdd.rst | 10 +- 50 files changed, 658 insertions(+), 60 deletions(-) rename docs/test/{ => libs}/github-actions-run.png (100%) rename docs/test/{ => libs}/github-actions.png (100%) rename docs/test/{ => libs}/hypothesis.rst (98%) create mode 100644 docs/test/libs/index.rst rename docs/test/{ => libs}/mock/assert_called.rst (100%) rename docs/test/{ => libs}/mock/autospec.rst (100%) rename docs/test/{ => libs}/mock/examples.rst (96%) rename docs/test/{ => libs}/mock/index.rst (100%) rename docs/test/{ => libs}/mock/limitations.rst (100%) rename docs/test/{ => libs}/mock/plugins.rst (100%) rename docs/test/{ => libs}/mock/spies.rst (100%) rename docs/test/{ => libs}/mock/test_mock.py (100%) rename docs/test/{ => libs}/pytest/api.png (100%) rename docs/test/{ => libs}/pytest/builtin-fixtures.rst (99%) rename docs/test/{ => libs}/pytest/ci.yaml (100%) rename docs/test/{ => libs}/pytest/command-line-options.rst (100%) rename docs/test/{ => libs}/pytest/config.rst (100%) rename docs/test/{ => libs}/pytest/coverage.png (100%) rename docs/test/{ => libs}/pytest/coverage.rst (100%) rename docs/test/{ => libs}/pytest/debug.rst (100%) rename docs/test/{ => libs}/pytest/examples.rst (100%) rename docs/test/{ => libs}/pytest/fixtures.rst (100%) rename docs/test/{ => libs}/pytest/functions.rst (100%) rename docs/test/{ => libs}/pytest/index.rst (92%) rename docs/test/{ => libs}/pytest/markers.rst (100%) rename docs/test/{ => libs}/pytest/missing.png (100%) rename docs/test/{ => libs}/pytest/params.rst (100%) rename docs/test/{ => libs}/pytest/plugins.rst (100%) rename docs/test/{ => libs}/pytest/test_one.py (100%) rename docs/test/{ => libs}/pytest/test_pytest.py (100%) rename docs/test/{ => libs}/pytest/test_two.py (100%) rename docs/test/{ => libs}/pytest/testsuite.rst (99%) rename docs/test/{ => libs}/test_arithmetic.py (100%) rename docs/test/{ => libs}/test_emails.py (100%) rename docs/test/{ => libs}/test_emails_2.py (100%) rename docs/test/{ => libs}/test_hypothesis.py (100%) rename docs/test/{ => libs}/test_mock.py (100%) rename docs/test/{ => libs}/test_pytest.py (100%) rename docs/test/{ => libs}/tox.rst (99%) rename docs/test/{ => libs}/unittest.rst (83%) rename docs/test/{ => methods}/bdd.rst (100%) create mode 100644 docs/test/methods/forms.py create mode 100644 docs/test/methods/index.rst create mode 100644 docs/test/methods/legacy.rst create mode 100644 docs/test/methods/solid.rst rename docs/test/{ => methods}/tdd.rst (95%) diff --git a/docs/appendix/glossary.rst b/docs/appendix/glossary.rst index 01961224..dd3a3d94 100644 --- a/docs/appendix/glossary.rst +++ b/docs/appendix/glossary.rst @@ -682,20 +682,20 @@ Glossary Various modules are available in Python: - :doc:`/test/unittest` + :doc:`/test/libs/unittest` supports you in the automation of tests. - :doc:`/test/mock/index` + :doc:`/test/libs/mock/index` allows you to create and use :term:`Mock` objects. :doc:`../document/doctest` allows you to test tests written in Python :term:`docstrings `. - :doc:`/test/tox` + :doc:`/test/libs/tox` allows you to test in different environments. Blackbox test is developed without knowledge of the source code. In addition to - :doc:`/test/unittest`, :doc:`/test/hypothesis` can also be used for such - tests in Python. + :doc:`/test/libs/unittest`, :doc:`/test/libs/hypothesis` can also be used + for such tests in Python. ``assert`` A keyword that stops code execution if its argument is false. @@ -739,8 +739,8 @@ Glossary correct methods were called. The Python library for mocks is :doc:`unittest.mock - <../test/mock/index>`. It is also supported by - :doc:`../test/pytest/index`. Alternatively, however, you can also use + <../test/lib/mock/index>`. It is also supported by + :doc:`../test/lib/pytest/index`. Alternatively, however, you can also use `pytest-mock `_. .. seealso:: @@ -782,7 +782,7 @@ Glossary These three steps are often summarised as *‘Red – Green – Refactor’*. .. seealso:: - * :doc:`../test/tdd` + * :doc:`../test/methods/tdd` * `Canon TDD `_ by Kent Beck * `Test-driven development by example diff --git a/docs/document/sphinx/test.rst b/docs/document/sphinx/test.rst index 79be059c..27aafb6a 100644 --- a/docs/document/sphinx/test.rst +++ b/docs/document/sphinx/test.rst @@ -93,7 +93,7 @@ Continuous integration If necessary, you can also check automatically in your :term:`CI` pipeline whether the documentation is being built and the links are valid. In -:doc:`../../test/tox`, the configuration can be added as follows: +:doc:`../../test/libs/tox`, the configuration can be added as follows: .. code-block:: ini :caption: tox.ini @@ -160,7 +160,7 @@ configuration: With :doc:`Sybil:index` you can not only check :doc:`rest`, but also :doc:`Markdown ` and :doc:`Myst `, for example. Sybil can also check code blocks in the documentation with either - :doc:`../../test/pytest/index` or :doc:`../../test/unittest`. + :doc:`../../test/pytest/libs/index` or :doc:`../../test/libs/unittest`. .. _test_code: @@ -369,8 +369,8 @@ example: * `Configuration `_ -You can now insert ``interrogate`` into your :doc:`../../test/tox` file, for -example with +You can now insert ``interrogate`` into your :doc:`../../test/libs/tox` file, +for example with .. code-block:: ini :caption: tox.ini diff --git a/docs/libs/batteries.rst b/docs/libs/batteries.rst index 6ef13100..adee76a9 100644 --- a/docs/libs/batteries.rst +++ b/docs/libs/batteries.rst @@ -160,7 +160,7 @@ Developing and debugging +-----------------------------------+-------------------------------------------------------------------------------+ | :py:mod:`doctest` | Test examples from Python docstrings | +-----------------------------------+-------------------------------------------------------------------------------+ -| :py:mod:`unittest` | Framework for unittests, see also :doc:`/test/unittest` | +| :py:mod:`unittest` | Framework for unittests, see also :doc:`/test/libs/unittest` | +-----------------------------------+-------------------------------------------------------------------------------+ | :py:mod:`test.support` | Utility functions for tests | +-----------------------------------+-------------------------------------------------------------------------------+ diff --git a/docs/test/index.rst b/docs/test/index.rst index b655e0f7..133aa5b4 100644 --- a/docs/test/index.rst +++ b/docs/test/index.rst @@ -15,10 +15,5 @@ Basically, a distinction is made between static and dynamic test procedures. :titlesonly: :hidden: - unittest - pytest/index - tox - mock/index - hypothesis - tdd - bdd + libs/index + methods/index diff --git a/docs/test/github-actions-run.png b/docs/test/libs/github-actions-run.png similarity index 100% rename from docs/test/github-actions-run.png rename to docs/test/libs/github-actions-run.png diff --git a/docs/test/github-actions.png b/docs/test/libs/github-actions.png similarity index 100% rename from docs/test/github-actions.png rename to docs/test/libs/github-actions.png diff --git a/docs/test/hypothesis.rst b/docs/test/libs/hypothesis.rst similarity index 98% rename from docs/test/hypothesis.rst rename to docs/test/libs/hypothesis.rst index 291d374e..16e5ec51 100644 --- a/docs/test/hypothesis.rst +++ b/docs/test/libs/hypothesis.rst @@ -78,8 +78,8 @@ Example using ``strategies`` and ``given`` :lineno-start: 1 #. For our test, we will now use ``hypothesis.given`` as a :doc:`dekorator - <../functions/decorators>` to convert the test function into a parameterised - one, which is then executed with a wide range of suitable data: + <../../functions/decorators>` to convert the test function into a + parameterised one, which is then executed with a wide range of suitable data: .. literalinclude:: test_hypothesis.py :language: python @@ -177,7 +177,7 @@ Example with regular expressions #. In the following example, we attempt to extract the ``username`` and ``domain`` with a :doc:`regular expression - <../types/strings/built-in-modules/regex>` from an email address using: + <../../types/strings/built-in-modules/regex>` from an email address using: .. literalinclude:: test_emails.py :lines: 1, 5-9 diff --git a/docs/test/libs/index.rst b/docs/test/libs/index.rst new file mode 100644 index 00000000..a40ab67c --- /dev/null +++ b/docs/test/libs/index.rst @@ -0,0 +1,32 @@ +Test libraries +============== + +:doc:`unittest` and :doc:`pytest/index` support the following testing concepts: + +.. glossary:: + + Test Case + tests a single scenario. + + Test Fixture + is a consistent test environment. + + Test Suite + is a collection of several :term:`test cases `. + + Test Runner + runs through a :term:`test suite` and displays the results. + +:doc:`tox` also provides various environments in which tests can be run. +Finally, :doc:`hypothesis` supports you with :term:`black-box testing +`. + +.. toctree:: + :titlesonly: + :hidden: + + unittest + pytest/index + tox + mock/index + hypothesis diff --git a/docs/test/mock/assert_called.rst b/docs/test/libs/mock/assert_called.rst similarity index 100% rename from docs/test/mock/assert_called.rst rename to docs/test/libs/mock/assert_called.rst diff --git a/docs/test/mock/autospec.rst b/docs/test/libs/mock/autospec.rst similarity index 100% rename from docs/test/mock/autospec.rst rename to docs/test/libs/mock/autospec.rst diff --git a/docs/test/mock/examples.rst b/docs/test/libs/mock/examples.rst similarity index 96% rename from docs/test/mock/examples.rst rename to docs/test/libs/mock/examples.rst index 09eaef5b..598add62 100644 --- a/docs/test/mock/examples.rst +++ b/docs/test/libs/mock/examples.rst @@ -124,7 +124,7 @@ CLI. To do this, we’ll use :func:`mock.patch.object` as a context manager: In our test code, we import ``tasks``. The resulting ``tasks`` object is what we are going to patch. The call to :func:`mock.patch.object`, used as a -:doc:`context manager <../../control-flow/with>` within a ``with`` block, +:doc:`context manager <../../../control-flow/with>` within a ``with`` block, returns a mock object that is cleaned up after the ``with`` block: #. In this case, the ``__version__`` attribute of ``tasks`` is replaced with @@ -146,7 +146,7 @@ In :file:`src/cusy/tasks/cli.py`, we have defined :func:`config` as follows: with tasks_db() as db: print(db.path()) -:func:`tasks_db` is a :doc:`context manager <../../control-flow/with>` that +:func:`tasks_db` is a :doc:`context manager <../../../control-flow/with>` that returns a ``tasks.TasksDB`` object. The returned object is then used as ``db`` to call :func:`db.path`. So we need to mock two things here: ``tasks.TasksDB`` and one of its methods, :func:`path`. Let’s start with the class: @@ -199,7 +199,7 @@ that tests can use it to substitute values for things like ``path``: assert result.stdout.rstrip() == "/foo/" Alternatively, the :func:`@mock.patch` :doc:`decorator -<../../functions/decorators>` can also be used to mock classes or objects. In +<../../../functions/decorators>` can also be used to mock classes or objects. In the following examples, the output of ``os.listdir`` is mocked. For this, ``db_path`` does not need to exist on the file system: diff --git a/docs/test/mock/index.rst b/docs/test/libs/mock/index.rst similarity index 100% rename from docs/test/mock/index.rst rename to docs/test/libs/mock/index.rst diff --git a/docs/test/mock/limitations.rst b/docs/test/libs/mock/limitations.rst similarity index 100% rename from docs/test/mock/limitations.rst rename to docs/test/libs/mock/limitations.rst diff --git a/docs/test/mock/plugins.rst b/docs/test/libs/mock/plugins.rst similarity index 100% rename from docs/test/mock/plugins.rst rename to docs/test/libs/mock/plugins.rst diff --git a/docs/test/mock/spies.rst b/docs/test/libs/mock/spies.rst similarity index 100% rename from docs/test/mock/spies.rst rename to docs/test/libs/mock/spies.rst diff --git a/docs/test/mock/test_mock.py b/docs/test/libs/mock/test_mock.py similarity index 100% rename from docs/test/mock/test_mock.py rename to docs/test/libs/mock/test_mock.py diff --git a/docs/test/pytest/api.png b/docs/test/libs/pytest/api.png similarity index 100% rename from docs/test/pytest/api.png rename to docs/test/libs/pytest/api.png diff --git a/docs/test/pytest/builtin-fixtures.rst b/docs/test/libs/pytest/builtin-fixtures.rst similarity index 99% rename from docs/test/pytest/builtin-fixtures.rst rename to docs/test/libs/pytest/builtin-fixtures.rst index 655f9096..fae68fc5 100644 --- a/docs/test/pytest/builtin-fixtures.rst +++ b/docs/test/libs/pytest/builtin-fixtures.rst @@ -478,7 +478,7 @@ Remaining built-in fixtures | | and similar options. | +-------------------------------+-----------------------------------------------+ | ``doctest_namespace`` | useful if you want to use pytest to perform | -| | :doc:`doctests <../../document/doctest>`. | +| | :doc:`doctests <../../../document/doctest>`. | +-------------------------------+-----------------------------------------------+ | ``pytestconfig`` | is used to get access to configuration values,| | | plugin managers and hooks. | diff --git a/docs/test/pytest/ci.yaml b/docs/test/libs/pytest/ci.yaml similarity index 100% rename from docs/test/pytest/ci.yaml rename to docs/test/libs/pytest/ci.yaml diff --git a/docs/test/pytest/command-line-options.rst b/docs/test/libs/pytest/command-line-options.rst similarity index 100% rename from docs/test/pytest/command-line-options.rst rename to docs/test/libs/pytest/command-line-options.rst diff --git a/docs/test/pytest/config.rst b/docs/test/libs/pytest/config.rst similarity index 100% rename from docs/test/pytest/config.rst rename to docs/test/libs/pytest/config.rst diff --git a/docs/test/pytest/coverage.png b/docs/test/libs/pytest/coverage.png similarity index 100% rename from docs/test/pytest/coverage.png rename to docs/test/libs/pytest/coverage.png diff --git a/docs/test/pytest/coverage.rst b/docs/test/libs/pytest/coverage.rst similarity index 100% rename from docs/test/pytest/coverage.rst rename to docs/test/libs/pytest/coverage.rst diff --git a/docs/test/pytest/debug.rst b/docs/test/libs/pytest/debug.rst similarity index 100% rename from docs/test/pytest/debug.rst rename to docs/test/libs/pytest/debug.rst diff --git a/docs/test/pytest/examples.rst b/docs/test/libs/pytest/examples.rst similarity index 100% rename from docs/test/pytest/examples.rst rename to docs/test/libs/pytest/examples.rst diff --git a/docs/test/pytest/fixtures.rst b/docs/test/libs/pytest/fixtures.rst similarity index 100% rename from docs/test/pytest/fixtures.rst rename to docs/test/libs/pytest/fixtures.rst diff --git a/docs/test/pytest/functions.rst b/docs/test/libs/pytest/functions.rst similarity index 100% rename from docs/test/pytest/functions.rst rename to docs/test/libs/pytest/functions.rst diff --git a/docs/test/pytest/index.rst b/docs/test/libs/pytest/index.rst similarity index 92% rename from docs/test/pytest/index.rst rename to docs/test/libs/pytest/index.rst index 291f7171..c91f589c 100644 --- a/docs/test/pytest/index.rst +++ b/docs/test/libs/pytest/index.rst @@ -18,9 +18,9 @@ module that simplifies testing even further. as functions, which promotes reusability and simplifies the management of test dependencies. * Parametrised tests are possible in unittest, but require additional effort. - pytest, however, includes the :doc:`decorator <../../functions/decorators>` - ``@pytest.mark.parametrize``, which makes it easy to run test functions with - different inputs and expected outputs. + pytest, however, includes the :doc:`decorator + <../../../functions/decorators>` ``@pytest.mark.parametrize``, which makes it + easy to run test functions with different inputs and expected outputs. * pytest has an extensive ecosystem with over 800 :doc:`plugins` for advanced testing requirements; unittest is more limited in its extensibility. diff --git a/docs/test/pytest/markers.rst b/docs/test/libs/pytest/markers.rst similarity index 100% rename from docs/test/pytest/markers.rst rename to docs/test/libs/pytest/markers.rst diff --git a/docs/test/pytest/missing.png b/docs/test/libs/pytest/missing.png similarity index 100% rename from docs/test/pytest/missing.png rename to docs/test/libs/pytest/missing.png diff --git a/docs/test/pytest/params.rst b/docs/test/libs/pytest/params.rst similarity index 100% rename from docs/test/pytest/params.rst rename to docs/test/libs/pytest/params.rst diff --git a/docs/test/pytest/plugins.rst b/docs/test/libs/pytest/plugins.rst similarity index 100% rename from docs/test/pytest/plugins.rst rename to docs/test/libs/pytest/plugins.rst diff --git a/docs/test/pytest/test_one.py b/docs/test/libs/pytest/test_one.py similarity index 100% rename from docs/test/pytest/test_one.py rename to docs/test/libs/pytest/test_one.py diff --git a/docs/test/pytest/test_pytest.py b/docs/test/libs/pytest/test_pytest.py similarity index 100% rename from docs/test/pytest/test_pytest.py rename to docs/test/libs/pytest/test_pytest.py diff --git a/docs/test/pytest/test_two.py b/docs/test/libs/pytest/test_two.py similarity index 100% rename from docs/test/pytest/test_two.py rename to docs/test/libs/pytest/test_two.py diff --git a/docs/test/pytest/testsuite.rst b/docs/test/libs/pytest/testsuite.rst similarity index 99% rename from docs/test/pytest/testsuite.rst rename to docs/test/libs/pytest/testsuite.rst index 99d5671d..b4d00514 100644 --- a/docs/test/pytest/testsuite.rst +++ b/docs/test/libs/pytest/testsuite.rst @@ -8,7 +8,8 @@ Arrange-Act-Assert (AAA) became popular as part of :term:`test-driven development (TDD) `. Given-When-Then (GWT) - is used in the context of behaviour-driven development (BDD). + is used in the context of :doc:`behaviour-driven development (BDD) + <../../methods/bdd>`. The division into these free phases has many advantages. This separates the parts diff --git a/docs/test/test_arithmetic.py b/docs/test/libs/test_arithmetic.py similarity index 100% rename from docs/test/test_arithmetic.py rename to docs/test/libs/test_arithmetic.py diff --git a/docs/test/test_emails.py b/docs/test/libs/test_emails.py similarity index 100% rename from docs/test/test_emails.py rename to docs/test/libs/test_emails.py diff --git a/docs/test/test_emails_2.py b/docs/test/libs/test_emails_2.py similarity index 100% rename from docs/test/test_emails_2.py rename to docs/test/libs/test_emails_2.py diff --git a/docs/test/test_hypothesis.py b/docs/test/libs/test_hypothesis.py similarity index 100% rename from docs/test/test_hypothesis.py rename to docs/test/libs/test_hypothesis.py diff --git a/docs/test/test_mock.py b/docs/test/libs/test_mock.py similarity index 100% rename from docs/test/test_mock.py rename to docs/test/libs/test_mock.py diff --git a/docs/test/test_pytest.py b/docs/test/libs/test_pytest.py similarity index 100% rename from docs/test/test_pytest.py rename to docs/test/libs/test_pytest.py diff --git a/docs/test/tox.rst b/docs/test/libs/tox.rst similarity index 99% rename from docs/test/tox.rst rename to docs/test/libs/tox.rst index 35b1ab2f..8897b501 100644 --- a/docs/test/tox.rst +++ b/docs/test/libs/tox.rst @@ -18,7 +18,7 @@ to test with different dependency configurations and different configurations for different operating systems. tox uses project information from the :file:`setup.py` or :file:`pyproject.toml` file for the package under test to create an installable :doc:`distribution of your package -<../packs/distribution>`. It searches for a list of environments in the +<../../packs/distribution>`. It searches for a list of environments in the ``[tool.tox]`` section of the :file:`pyproject.toml` file, and then performs the following steps for each one: diff --git a/docs/test/unittest.rst b/docs/test/libs/unittest.rst similarity index 83% rename from docs/test/unittest.rst rename to docs/test/libs/unittest.rst index 22b4f07b..1e5a35e4 100644 --- a/docs/test/unittest.rst +++ b/docs/test/libs/unittest.rst @@ -5,22 +5,6 @@ Unittest shared setup and tear-down code as well as aggregation and independence of tests. -It provides the following test concepts: - -.. glossary:: - - Test Case - tests a single scenario. - - Test Fixture - is a consistent test environment. - - Test Suite - is a collection of several :term:`test cases `. - - Test Runner - runs through a :term:`Test Suite` and displays the results. - Example ------- @@ -119,19 +103,19 @@ Example: Testing an SQLite database ----------------------------------- #. To test whether the database ``library.db`` was created with - :download:`create_db.py <../save-data/sqlite/create_db.py>`, we import - :download:`../save-data/sqlite/create_db.py` and :doc:`os + :download:`create_db.py <../../save-data/sqlite/create_db.py>`, we import + :download:`../../save-data/sqlite/create_db.py` and :doc:`os ` in addition to :doc:`sqlite3 ` and :doc:`unittest `: - .. literalinclude:: ../save-data/sqlite/test_sqlite.py + .. literalinclude:: ../../save-data/sqlite/test_sqlite.py :language: python :lines: 1-5 :lineno-start: 1 #. Then we first define a test class ``TestCreateDB``: - .. literalinclude:: ../save-data/sqlite/test_sqlite.py + .. literalinclude:: ../../save-data/sqlite/test_sqlite.py :language: python :lines: 8 :lineno-start: 8 @@ -140,7 +124,7 @@ Example: Testing an SQLite database ``assert`` to assume that the file exists in :doc:`os.path `: - .. literalinclude:: ../save-data/sqlite/test_sqlite.py + .. literalinclude:: ../../save-data/sqlite/test_sqlite.py :language: python :lines: 9-10 :lineno-start: 9 @@ -149,7 +133,7 @@ Example: Testing an SQLite database create the table again and expect with ``assertRaises`` that ``sqlite`` is terminated with an ``OperationalError``: - .. literalinclude:: ../save-data/sqlite/test_sqlite.py + .. literalinclude:: ../../save-data/sqlite/test_sqlite.py :language: python :lines: 12-14 :lineno-start: 12 @@ -157,7 +141,7 @@ Example: Testing an SQLite database #. We do not want to carry out further tests on a database in the file system but in an SQLite database in the working memory: - .. literalinclude:: ../save-data/sqlite/test_sqlite.py + .. literalinclude:: ../../save-data/sqlite/test_sqlite.py :language: python :lines: 17-20 :lineno-start: 17 diff --git a/docs/test/bdd.rst b/docs/test/methods/bdd.rst similarity index 100% rename from docs/test/bdd.rst rename to docs/test/methods/bdd.rst diff --git a/docs/test/methods/forms.py b/docs/test/methods/forms.py new file mode 100644 index 00000000..83a0e515 --- /dev/null +++ b/docs/test/methods/forms.py @@ -0,0 +1,55 @@ +import gc + + +class Form: + + def __init__(self, x=0, y=0): + self.x = x + self.y = y + + def move(self, delta_x, delta_y): + self.x = self.x + delta_x + self.y = self.y + delta_y + + +class Square(Form): + def __init__(self, length=1, x=0, y=0): + super().__init__(x, y) + self.length = length + + def circumference(self): + return 4 * self.length + + +class Circle(Form): + pi = 3.14159 + + def __init__(self, diameter=1, x=0, y=0): + super().__init__(x, y) + self.diameter = diameter + + def circumference(self): + return self.diameter * Circle.pi + + +class SquaresAndCircles: + pi = 3.14159 + + @classmethod + def circumferences(cls): + csum = 0 + for obj in gc.get_objects(): + if isinstance(obj, Square): + csum = csum + 4 * obj.length + if isinstance(obj, Circle): + csum = csum + obj.diameter * cls.pi + return csum + + +class CircumferenceFormInstances: + def circumferences(): + csum = 0 + for obj in gc.get_objects(): + if isinstance(obj, Form) and hasattr(obj, "circumference"): + csum = csum + obj.circumference() + return csum diff --git a/docs/test/methods/index.rst b/docs/test/methods/index.rst new file mode 100644 index 00000000..483661bf --- /dev/null +++ b/docs/test/methods/index.rst @@ -0,0 +1,16 @@ +Testing methods +=============== + +:doc:`tdd` is the best-known testing methodology; :doc:`bdd` builds on this, but +focuses more strongly on the requirements and behaviour of the software. In the +case of :doc:`legacy`, we then take a closer look at how test-driven development +can be applied to an untested codebase. + +.. toctree:: + :titlesonly: + :hidden: + + tdd + bdd + legacy + solid diff --git a/docs/test/methods/legacy.rst b/docs/test/methods/legacy.rst new file mode 100644 index 00000000..174a3298 --- /dev/null +++ b/docs/test/methods/legacy.rst @@ -0,0 +1,307 @@ +Legacy software +=============== + +There may be various reasons for wanting to modify existing software: + +* to add a feature +* to fix a bug +* to improve the software architecture (→ :ref:`refactoring`) +* to improve resource usage + +If an existing codebase lacks significant test coverage, existing code is often +modified and then checked to see whether the desired feature is working or the +bug has been fixed. One might also check whether the change has broken other +features; nevertheless, it remains uncertain whether all the implications of the +code change have been taken into account. + +In :doc:`test-driven development ` for legacy software, tests are first +written for the code to be modified and for all code that depends on it. With +such :term:`regression tests `, we can identify changes and +determine whether the software still functions exactly as it did in the past. +This ensures that only the intended changes are made. However, regression tests +are usually carried out at the application interface, which means they present a +number of problems: + +Error localisation + The further tests stray from what you are actually supposed to be testing, + the more difficult it becomes to identify the root cause of the error. +Execution time + Larger tests also take longer to run. This means that test runs can take a + frustratingly long time. Tests that take too long to run are usually carried + out much less frequently. + +Unit tests make it easier to localise errors and reduce execution time. Unlike + +* sections of code can be tested independently of one another +* tests can be grouped so that, under certain conditions, only some are executed + whilst others are run under different conditions. +* they help us pinpoint errors quickly. + +So why don’t we simply write unit tests? Often, dependency issues prevent this. +When objects depend directly on something that is difficult to use in a test, +these dependencies are also difficult to change and manage. Often, a large part +of the work on legacy code involves breaking down such dependencies so that +changes can be made more easily. Consequently, we are often unable to set up +unit tests without first modifying the code. Unit tests are therefore not very +practical in such cases. + +By resolving dependencies, we can write tests that make more far-reaching +changes safer. However, such initial refactorings should be carried out very +conservatively, so that the risk of introducing errors remains low. If we do +this, the code in that area may end up looking slightly less elegant. + + *“They are like the incision points in surgery: There might be a scar left + in your code after your work, but everything beneath it can get better.”* + +– `Working Effectively with Legacy Code +`_ by +Michael C. Feathers + +The aim with legacy code is to make functional changes that add value whilst, at +the same time, incorporating a larger part of the system into the tests. At the +end of each development cycle, we should be able to point not only to code that +provides a new function, but also to the associated tests. In future, working on +code that has already been tested will become much easier. You can follow these +steps when you need to make changes to legacy code: + +#. **Identify the section of code to be modified.** Where changes need to be + made depends heavily on the architecture. +#. :ref:`find-test-opportunities`: In some cases, it is easy to find suitable + places to write tests, but with legacy code this can often be difficult. +#. :ref:`resolve-dependencies`: Dependencies are often the most obvious obstacle + to testing, as they cause difficulties in test environments when + instantiating objects or executing methods. With legacy code, dependencies + often need to be decoupled in order to set up tests. Ideally, we would have + tests to show us whether the measures we take to decouple dependencies have + themselves caused problems – but this is often not the case. +#. :ref:`write-tests`: Tests for legacy code may differ slightly from those for + new code. +#. :ref:`refactoring`: Once we have made changes to the legacy code, we are + often more familiar with its issues, and the tests we wrote to add + functionality often provide us with a degree of assurance that allows us to + carry out refactoring. This often means that the code has become a little + easier to maintain than before. But do not underestimate this work: simple + measures – such as splitting up a large class – can make a significant + difference in applications, even if they seem somewhat mechanical. + +.. _find-test-opportunities: + +Finding testing opportunities +----------------------------- + +Sprout +~~~~~~ + +You can use Sprout when you need to add a function or class to a system and it +can be completely rewritten. Write the code at the point where the new +functionality is required. You may not be able to test the call sites straight +away, but at least you can write tests for your new code. + +Essentially, however, this means we are giving up on improving and testing the +original function or class. We’re simply adding new features. Nevertheless, this +is sometimes the most practical approach, even if it leaves the code in a sort +of limbo: it’s not really clear why this particular function or class is located +elsewhere. On the other hand, the new code is clearly separated from the old: +your changes can be viewed in isolation and have a clean interface with the old +code. + +Wrap +~~~~ + +For wrap, a function is created with the same name as the original function, and +this then points to our original code. Using this approach, we can add new +behaviour or a new call to the original function. This ensures that all +responsibilities appear to be clearly separated from one another. Here are the +steps for this wrap method: + +#. Identify the method you need to change +#. If the change can be expressed as a single sequence of instructions in one + place, rename the function and then create a new function with the same name + and signature as the old method. Make sure to retain the signatures. +#. Insert a call to the old function within the new function. +#. Develop a new function and test it first. + +One potential drawback is that the new function must not be intertwined with the +logic of the old function. It must be something that is executed either before +or after the old function. In reality, this isn’t really a drawback at all. A +serious drawback, however, is that a new name must be found for the old code. + +Another form of the wrap method, which we can use when we simply want to add a +new function, does not have this problem. The steps are then as follows: + +#. Identify a function that you need to change +#. If the change can be expressed as a single sequence of statements in one + place, develop a new function for this using test-driven development +#. Create another function that calls both the new and the old functions. + +Wrap has the advantage over Sprout in that it does not increase the existing +scope. Furthermore, the new functionality is independent of the existing +functionality, and code intended for one purpose is not intertwined with code +intended for another. + +When we apply Wrap to classes, this is known as the *Decorator pattern*. We +create objects of a class that wraps another class and pass these on. The +wrapping class should have the same interface as the wrapped class, so that +clients do not realise they are working with a wrapper. The Decorator pattern +allows complex behaviours to be built up at runtime through the composition of +objects. + +.. admonition:: Decorator Pattern + :collapsible: closed + + Decorator is a structural pattern that provides a flexible alternative to + subclassing for extending a class with additional functionality. It should + not be confused with Python :doc:`decorators <../../functions/decorators>`. + + You can find an example of the `Decorator Pattern + `_ on the Python Wiki. It + shows us how decorators are incorporated into the pipeline to dynamically + inject various behaviours into an object. + +Although the Decorator pattern is useful, it should be used sparingly: + + *“Navigating through code that contains decorators that decorate other + decorators is a lot like peeling away the layers of an onion. It is + necessary work, but it does make your eyes water.”* + +– `Working Effectively with Legacy Code +`_ +by Michael C. Feathers + +If the new behaviour only needs to be applied in a few places, it may therefore +be useful to create a wrapper that does not follow the Decorator pattern. Over +time, you should keep an eye on the wrapper’s responsibilities and consider +whether it could evolve into a broader concept within your system. Here are the +steps for the wrap class: + +#. Identify a method where you need to make the change. +#. If the change can be expressed as a single sequence of statements in one + place, create a class that accepts the class to be wrapped as a constructor + argument. If you find it difficult to create a class that wraps the original + class, you may need to extract functions or interfaces from the wrapped class + so that you can instantiate your wrapper. +#. Using test-driven development, create a method within this class that + performs the new task. Write another method that calls both the new method + and the old method of the wrapped class. +#. Instance the wrapper class in your code at the point where you wish to + activate the new behaviour. + +.. _resolve-dependencies: + +Resolving dependencies +---------------------- + +Systems that are broken down into small, clearly named and understandable parts +allow you to work more quickly. Many dependencies are problematic, but +fortunately they can be resolved. With object-oriented code, the first step is +often to instantiate the required classes in a :term:`test fixture `. + +If you have a class instance that needs to be modified in a test, this is +generally very quick. However, if this requires access to external resources +such as a database, hardware or communications infrastructure, it quickly +becomes time-consuming. In such cases, it is worth checking everything that +depends on what you want to instantiate. You should then define interfaces and +move the dependencies into new modules. + +.. admonition:: Dependency Inversion Principle + :collapsible: closed + + The `Dependency Inversion Principle + `_ states that + your code’s dependencies are much lower when it depends on an interface. + Interfaces generally change far less frequently than the underlying code. You + can then modify classes or implement the interface without having to change + the underlying code. For this reason, it is better to rely on interfaces or + abstract classes rather than concrete classes. By relying on things that + change less frequently, you minimise the likelihood that certain changes will + trigger extensive reworking. + +We can decouple dependencies and distribute classes across different modules so +that we can run our tests quickly and receive feedback, thereby reducing the +error rate. However, this comes at a price: more interfaces and modules entail +conceptual overhead. Ultimately, you end up with sections of code that are +easier to work with. It may be a little more laborious to test a small group of +classes separately, but it is important to remember that they do not need to be +tested when another group of classes is being tested. + +Programming by Difference +~~~~~~~~~~~~~~~~~~~~~~~~~ + +In object-oriented programming, we can use inheritance to introduce +functionality without having to modify a class directly. Once we have added the +functionality, we can work out exactly how we want to integrate it. This +*programming by difference* is useful for making changes quickly. However, +certain pitfalls, such as breaching the :doc:`solid`, should be avoided. + +.. _write-tests: + +Writing tests +------------- + +It’s not always easy to instantiate a class in a test fixture. Here are the four +most common problems we encounter: + +* Objects of the class cannot be created easily. +* The test fixture cannot be built easily using the class. +* The constructor we need to use has undesirable side effects. +* Extensive calculations are carried out in the constructor, and we need to + capture these. + +There is a whole arsenal of techniques for tackling these problems: + +Interfering configurations, environment variables, paths and parameters +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To check whether these details are actually being used, we can simply pass +:doc:`../../types/none` where appropriate. The worst that can happen is that +part of the code attempts to use this parameter and throws an :doc:`exception +<../../control-flow/exceptions>`. Alternatively, the method that handles this +can be overridden using :ref:`monkeypatch +`. However, we must ensure +that we do not alter the behaviour we are trying to test. + +Hidden resources +~~~~~~~~~~~~~~~~ + +Often, a hidden resource – such as an SMTP server – is used, which we cannot +easily access in our test fixture. *Parameterize constructor* externalises such +a resource and then passes it as a parameter. + +.. _refactoring: + +Refactoring +----------- + +We will illustrate what refactoring might look like using two different +examples: + +* **Library dependencies:** A library that solves a specific problem for us + often saves us a great deal of time on a project. However, they should not be + used indiscriminately throughout the code, as otherwise switching libraries + could be tantamount to rewriting the entire programme. + +* **Refactoring API calls:** Essentially, there are two approaches to + refactoring API calls: + + * With *Skin and Wrap* of the API, we create interfaces that mirror the API as + closely as possible, and then we create wrappers around the library’s + functions. Ultimately, we have no dependencies on the underlying API code, + and the wrappers can delegate to the real API in production code, whilst we + use :term:`fakes ` during testing. + + *Skin and Wrap* is well suited when + + * the API is relatively small + * you wish to completely decouple your dependencies from a third-party + library + * you have no tests and are unable to write any, as you cannot test the API. + We then have the option to test our entire code – with the exception of a + thin delegation layer from the wrapper to the actual API classes. + + * With *Responsibility-Based Extraction*, we identify responsibilities in the + + *Responsibility-Based Extraction* is more suitable if + + * the API is more complex + * you already have a tool with extraction methods diff --git a/docs/test/methods/solid.rst b/docs/test/methods/solid.rst new file mode 100644 index 00000000..da5cd292 --- /dev/null +++ b/docs/test/methods/solid.rst @@ -0,0 +1,208 @@ +SOLID principles +================ + +`SOLID `_ is an acronym for the first five +principles of object-oriented design (OOD) by Robert C. Martin (also known as +`Uncle Bob `_). + +These principles set out practices for developing software with a view to +maintainability and extensibility as the project grows. Adopting these +principles can also help to avoid code smells, refactor code and develop agile +or adaptive software. + +SOLID stands for: + +S – :ref:`single-responsibility` + A class’s methods should be focused on a single purpose. +O – :ref:`open-closed` + Objects should be open for extension but closed for modification. +L – :ref:`liskov-substitution` + Subclasses should be substitutable for their superclasses. +I – :ref:`interface-segregation` + Objects should not depend on methods they do not use. +D – :ref:`dependency-inversion` + Abstractions should not depend on details. + +.. _single-responsibility: + +Single Responsibility Principle +------------------------------- + +The `Single Responsibility Principle +`_ states that +each class should fulfil only one task: + + A class should have one, and only one, reason to change. + +– `SRP: The Single Responsibility Principle +`_ by Robert C. Martin + +Let’s take, for example, an application that takes a collection of shapes – +circles and squares – and calculates the sum of the perimeters of all the shapes +in the collection. + +First, create the :class:`Form` classes with the necessary parameters. For +squares, this is the side length, and for circles, the diameter: + +.. literalinclude:: forms.py + :language: python + :lines: 4, 6-8, 13-18, 22-24, 27-29 + +Now you can create a class called :class:`SquaresAndCircles` containing the +logic for calculating the perimeters of all squares and circles: + +.. literalinclude:: forms.py + :language: python + :lines: 1-3, 35-46 + +The :class:`SquaresAndCircles` class handles the logic required to calculate the +perimeters of all squares and circles. This fulfils the Single Responsibility +Principle. + +.. _open-closed: + +Open-Closed Principle +--------------------- + +The `Open-Closed Principle +`_ states: + + Modules should be both open (for extension) and closed (for modification). + +Accordingly, the code would require very little modification to add new +functionality, for example, via a subclass. + +Let’s look at the :class:`SquaresAndCircles` class and focus on the +:func:`circumferences` method. Imagine a scenario in which the sum of additional +shapes, such as triangles, pentagons, hexagons, :abbr:`etc. (et cetera)`, needs +to be calculated. You would have to constantly edit this class and add further +``if`` blocks. That would violate the :ref:`open-closed`. One way to improve +this method is to remove the logic for calculating the circumference of each +shape from the :class:`SquaresAndCircles` class and attach it to the classes for +the specific shapes. Here, the circumference calculations are defined in the +:class:`Square` and :class:`Circle` classes: + +.. literalinclude:: forms.py + :language: python + :lines: 15-32 + +The sum method :func:`circumferences` in the :class:`CircumferenceFormInstances` +class can then be rewritten as follows: + +.. literalinclude:: forms.py + :language: python + :lines: 49- + +This fulfils the Open-Closed Principle. + +.. tip:: + If your code is not yet open to new requirements, you should first reorganise + (refactor) the existing code so that it is open to the new functionality. + Only then should you add new code. + + Refactoring refers to the process of modifying a software system in such + a way that the external behaviour of the code remains unchanged, whilst + its internal structure is improved. + + – `Refactoring + `_ + by Martin Fowler + +.. note:: + Safe refactoring relies on :doc:`tests <../index>`. If you are genuinely + restructuring the code without changing its behaviour, the existing tests + should continue to pass at every stage. The tests act as a safety net that + justifies your confidence in the new structure of the code. If they fail, + + * you have inadvertently broken the code, + * or the existing tests are faulty. + +.. _liskov-substitution: + +Liskov Substitution Principle +----------------------------- + +The `Liskov Substitution Principle +`_ states that a +programme which uses objects of the base class must also function correctly with +objects of the subclass. There are two rules of thumb that are helpful for +adhering to the Liskov Substitution Principle: + +#. Avoid overriding concrete methods wherever possible. +#. If you do so nonetheless, check whether you can call the overridden method + from within the overriding method. + +Let’s extend the :class:`Form` class so that classes derived from it can be +moved in the x and y directions: + +.. literalinclude:: forms.py + :language: python + :lines: 4-12 + :emphasize-lines: 7-9 + +You can then move both squares and circles along the x- and y-axes: + +.. code-block:: pycon + + >>> import forms + >>> s1 = forms.Square() + >>> c1 = forms.Circle() + >>> s1.x, s1.y, c1.x, c1.y + (0, 0, 0, 0) + >>> s1.move(4, 5) + >>> c1.move(2, 3) + >>> s1.x, s1.y, c1.x, c1.y + (4, 5, 2, 3) + +.. note:: + The Liskov Substitution Principle also applies to :ref:`duck-typing`: any + object that claims to be a duck must fully implement the duck’s API. Duck + types should be interchangeable. Applying logic across different data types + of objects is known as `polymorphism + `_. + +.. _interface-segregation: + +Interface Segregation Principle +------------------------------- + +The `Interface Segregation Principle +`_ applies the +:ref:`single-responsibility` to interfaces in order to isolate specific +behaviour. If a change is required to part of your code, extracting an object +that plays a particular role makes it possible to support the new behaviour +without having to modify the existing code. This is preferable to hard-coded +specialisations. + +In the previous example, for instance, we checked whether our :obj:`Form` object +actually provided a :func:`circumference` method. This is necessary in case +shapes such as :class:`Point` or :class:`Line` are added later, which do not +have a circumference. + +.. note:: + In this context, the `Law of Demeter + `_ is also of interest; it + states that objects should only communicate with objects in their immediate + vicinity. This effectively restricts the list of other objects to which an + object can send a message and reduces coupling between objects: an object + can only communicate with its neighbours, but not with the neighbours of its + neighbours; objects can only send messages to those directly involved. + +.. _dependency-inversion: + +The Dependency Inversion Principle +---------------------------------- + +The `Dependency Inversion Principle +`_ can be defined +as follows: + + Abstractions should not depend on details. Details (concrete + implementations) should depend on abstractions. + +– `The Dependency Inversion Principle +`_ by Robert C. +Martin + +:func:`circumferences` should not be defined within the :class:`Forme` class, +as there are shapes without a circumference. diff --git a/docs/test/tdd.rst b/docs/test/methods/tdd.rst similarity index 95% rename from docs/test/tdd.rst rename to docs/test/methods/tdd.rst index 4e4ff0eb..5209f5d5 100644 --- a/docs/test/tdd.rst +++ b/docs/test/methods/tdd.rst @@ -52,7 +52,7 @@ Only then does he outline the following five steps:: * A number of the appropriate type should be returned, which may also be an integer. * If the set or sequence is empty, an error message should be displayed. - * If one or more elements are :doc:`../types/strings/index`, an attempt + * If one or more elements are :doc:`../../types/strings/index`, an attempt should be made to convert them into numbers of the appropriate type. * If the conversion of individual elements into numbers fails, an appropriate error message should be displayed. @@ -80,11 +80,11 @@ Only then does he outline the following five steps:: assert mean(ls) == mean(tp) == mean(st) == 2 We have simply defined that the function should be called :func:`mean` and - that it can take a :doc:`../types/sequences-sets/lists`, a - :doc:`../types/sequences-sets/tuples` or a - :doc:`../types/sequences-sets/sets` as a parameter. + that it can take a :doc:`../../types/sequences-sets/lists`, a + :doc:`../../types/sequences-sets/tuples` or a + :doc:`../../types/sequences-sets/sets` as a parameter. - By using the :doc:`decorator <../functions/decorators>` + By using the :doc:`decorator <../../functions/decorators>` :func:`@pytest.mark.xfail`, we expect this test to fail initially. Next, we’ll write a minimal version of :func:`mean` that should cause our From 21363508c0d31fd5fd1c259fa281c32e2240d1b3 Mon Sep 17 00:00:00 2001 From: veit Date: Sun, 4 Oct 2026 19:19:52 +0200 Subject: [PATCH 2/8] =?UTF-8?q?:memo:=20Add=20what=E2=80=99s=20new=20in=20?= =?UTF-8?q?Python=203.15?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add lacy imports * Add frozendict * Add unpacking in comprehensions --- CHANGELOG.rst | 6 +++++ docs/control-flow/loops.rst | 21 +++++++++++++++++ docs/modules/index.rst | 38 ++++++++++++++++++++++++++++++ docs/types/dicts.rst | 40 ++++++++++++++++++++++++++++++++ docs/types/index.rst | 3 +++ docs/types/strings/encodings.rst | 2 ++ 6 files changed, 110 insertions(+) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 359063d2..40ae9cb5 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -19,6 +19,12 @@ emergencies when we need to start branches for older versions. Added ~~~~~ +* 📝 Add what’s new in Python 3.15 + + * Add lacy imports + * Add frozendict + * Add unpacking in comprehensions + * 📝 Add timezones * 📝 Add pytest-leak-finder diff --git a/docs/control-flow/loops.rst b/docs/control-flow/loops.rst index ed5af094..27d277cd 100644 --- a/docs/control-flow/loops.rst +++ b/docs/control-flow/loops.rst @@ -180,6 +180,27 @@ Das allgemeine Format für Dict Comprehensions ist: :samp:`{NEW_DICT} = \{{KEY}: {VALUE} for {MEMBER} in {ITERABLE}\}` +.. _unpacking_in_comprehensions: + +Unpack +~~~~~~ + +.. versionadded:: 3.15 + + In line with :pep:`798`, :doc:`../types/sequences-sets/lists`, + :doc:`../types/sequences-sets/sets` and :doc:`../types/dicts` now support + comprehensions using ``*`` and ``**``: + + .. code-block:: pycon + + >>> nested_list = [[0, 1], [2, 3], [4, 5]] + >>> [*l for l in nested_list] + [0, 1, 2, 3, 4, 5] + >>> + >>> nested_dict = [{0: "a"}, {1: "b"}, {2: "c"}] + >>> {**d for d in nested_dict} + {0: 'a', 1: 'b', 2: 'c'} + Change a ``Collection`` ~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/modules/index.rst b/docs/modules/index.rst index 6bbd8d1d..238bacee 100644 --- a/docs/modules/index.rst +++ b/docs/modules/index.rst @@ -48,6 +48,44 @@ provided via special modules that you can load as needed. .. seealso:: * :ref:`python3:py-modindex` +.. _explicit-lazy-imports: + +.. versionadded:: 3.15 + + Python 3.15 introduces explicit lazy imports via :pep:`810`: if an ``import`` + statement is prefixed with the keyword ``lazy``, the module is not loaded + immediately; instead, a proxy object is created. The actual module is loaded + the first time it is used: + + .. code-block:: pycon + + >>> import sys + >>> lazy import json + >>> lazy from pathlib import Path + >>> "json" in sys.modules + False + >>> with Path.open("books.json") as f: + ... data = json.load(f) + ... + >>> "json" in sys.modules + True + + If you cannot use ``lazy`` directly, for example in older versions of Python, + you can define a :attr:`~module.__lazy_modules__` module as a container whose + import statements are handled by ``lazy``: + + .. code-block:: pycon + + >>> __lazy_modules__ = {"json"} + >>> import json + >>> import sys + + Python 3.14 and earlier ignore ``__lazy_modules__``, whilst 3.15 and later + use the ``lazy`` variant. + + .. seealso:: + * :ref:`lazy-imports` + Creating modules ---------------- diff --git a/docs/types/dicts.rst b/docs/types/dicts.rst index ce4886d8..72994aee 100644 --- a/docs/types/dicts.rst +++ b/docs/types/dicts.rst @@ -109,6 +109,46 @@ keys of a dict, for example: >>> collections.Counter(titles) Counter({'Lists': 2, 'Data types': 1, 'Sets': 1}) +.. _frozendict: + +``frozendict`` +-------------- + +.. versionadded:: 3.15 + + :pep:`814` introduces :class:`python3:frozendict`, an :term:`immutable` + dictionary: + + .. code-block:: pycon + + >>> titles = frozendict({7.0: "Data Types", 7.1: "Lists", 7.2: "Tuples"}) + >>> titles + frozendict({7.0: 'Data Types', 7.1: 'Lists', 7.2: 'Tuples'}) + >>> titles[7.3] = "Sets" + Traceback (most recent call last): + File "", line 1, in + titles[7.3] = "Sets" + ~~~~~~^^^^^ + TypeError: 'frozendict' object does not support item assignment + + Immutable mappings are hashable, which means they can be used as keys in + dictionaries, as elements in :doc:`sets `, or accepted + as arguments by functions :doc:`decorated <../functions/decorators>` with + :func:`@functools.lru_cache`: + + .. code-block:: pycon + + >>> hash(titles) + 3827265406416199624 + + The merge operator (``|``) can be used to merge two ``frozendict`` objects or + a ``frozendict`` object with a ``dict`` object, for example: + + .. code-block:: pycon + + >>> titles | new_titles + frozendict({7.0: 'Data types', 7.1: 'Lists', 7.2: 'Tuples', 7.3: 'Sets'}) + Extensions ---------- diff --git a/docs/types/index.rst b/docs/types/index.rst index 5f9b329d..2d5cf760 100644 --- a/docs/types/index.rst +++ b/docs/types/index.rst @@ -40,6 +40,9 @@ appropriate special method attributes. Python has several built-in data types, from scalars like numbers and boolean values to more complex structures like lists, dictionaries and files. +.. seealso:: + * :doc:`python3:builtins/stdtypes` + .. toctree:: :titlesonly: :hidden: diff --git a/docs/types/strings/encodings.rst b/docs/types/strings/encodings.rst index 8e58ff86..583d5b7e 100644 --- a/docs/types/strings/encodings.rst +++ b/docs/types/strings/encodings.rst @@ -111,6 +111,8 @@ defines several different encodings from a single character set. UTF-8 is an encoding scheme for representing Unicode characters as binary data with one or more bytes per character. +.. _default-encoding: + .. versionadded:: 3.15 Python 3.15 uses UTF-8 as the default encoding, regardless of the system environment. This means that I/O operations without explicit encoding, for From ab7c30e08a1f967fe990a1ba0344438125312bda Mon Sep 17 00:00:00 2001 From: veit Date: Tue, 6 Oct 2026 14:07:14 +0200 Subject: [PATCH 3/8] :arrow_up: Update GH actions, pyproject and pre-commit checks --- .github/workflows/pages.yml | 2 +- .github/workflows/zizmor.yml | 2 +- .pre-commit-config.yaml | 4 ++-- pyproject.toml | 1 + 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 777f357a..fb5e330e 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -60,4 +60,4 @@ jobs: path: docs/_build/html - name: Deploy to GitHub Pages id: deployment - uses: actions/deploy-pages@cd2ce8fcbc39b97be8ca5fce6e763baed58fa128 # v5.0.0 + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml index a637c952..26d5335b 100644 --- a/.github/workflows/zizmor.yml +++ b/.github/workflows/zizmor.yml @@ -26,6 +26,6 @@ jobs: persist-credentials: false - name: Run zizmor - uses: zizmorcore/zizmor-action@70fb788f84895a7701f5643d103d587e460b5c99 # v0.6.3 + uses: zizmorcore/zizmor-action@cc914d7f3750a2d13d75c7f184a1060aa0e9d482 # v0.6.4 with: persona: pedantic diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index c1461c6d..68298787 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -15,7 +15,7 @@ repos: - id: check-added-large-files args: ['--maxkb=1024'] - repo: https://github.com/tox-dev/pyproject-fmt - rev: 3b42b9776870badc9eaffdef9a4a0834b764d87c # frozen: v2.29.3 + rev: 59e7b26529dc6f15c43063064b8b06ded60d0910 # frozen: v2.29.4 hooks: - id: pyproject-fmt - repo: https://github.com/abravalheri/validate-pyproject @@ -28,7 +28,7 @@ repos: - id: sphinx-lint types: [rst] - repo: https://github.com/pycqa/isort - rev: 131f4adcd5582bfc53928ab0d740eceb8b506b6c # frozen: 9.0.1 + rev: 9f905615631c545f5aea2516508109350d1d2f7d # frozen: 9.0.2 hooks: - id: isort additional_dependencies: ["toml"] diff --git a/pyproject.toml b/pyproject.toml index e96f3a56..d26f22e0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,6 +17,7 @@ classifiers = [ "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: 3.15", ] dependencies = [ "dask", From e4bd17de44e24f1319c35f9fb1f4027b84acb8bb Mon Sep 17 00:00:00 2001 From: veit Date: Mon, 12 Oct 2026 17:09:55 +0200 Subject: [PATCH 4/8] :arrow_up: Switch to Python 3.15, remove 3.10 * Use latest in rtd config * Use base_python_file --- .python-version | 2 +- .readthedocs.yaml | 2 +- docs/install.rst | 20 ++++++++++---------- docs/packs/dataprep/pyproject.toml | 4 ++-- docs/test/libs/pytest/debug.rst | 6 +++--- pyproject.toml | 3 +-- 6 files changed, 18 insertions(+), 19 deletions(-) diff --git a/.python-version b/.python-version index 6324d401..93a848f9 100644 --- a/.python-version +++ b/.python-version @@ -1 +1 @@ -3.14 +3.15 diff --git a/.readthedocs.yaml b/.readthedocs.yaml index f352e4e5..feedec6b 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -13,7 +13,7 @@ build: - plantuml tools: - python: "3.14" + python: latest python: # See https://docs.readthedocs.com/platform/stable/build-customization.html#install-dependencies-with-uv diff --git a/docs/install.rst b/docs/install.rst index df08c006..5d47813a 100644 --- a/docs/install.rst +++ b/docs/install.rst @@ -3,8 +3,8 @@ Installation Installing Python can be easy. The first step is to download the latest version from `www.python.org/downloads `_. The -tutorial is based on Python 3.14.0, but if you have Python 3.10 or newer -installed, this should not be a problem. +tutorial is based on Python 3.15.0, but if you have Python 3.11 or newer +installed, this usually isn’t a problem either. .. tab:: Linux @@ -19,9 +19,9 @@ installed, this should not be a problem. .. code-block:: console - $ wget https://www.python.org/ftp/python/3.14.0/Python-3.14.0.tgz - $ tar xf Python-3.14.0.tgz - $ cd Python-3.14.0 + $ wget https://www.python.org/ftp/python/3.15.0/Python-3.15.0.tgz + $ tar xf Python-3.15.0.tgz + $ cd Python-3.15.0 $ ./configure --enable-optimizations $ sudo make altinstall @@ -51,11 +51,11 @@ installed, this should not be a problem. #. Download the latest Python Releases for Windows installer, for example `Windows installer (64-bit) - `_. + `_. #. Start the installation programme. If you have the necessary authorisations, install Python with the option *Install launcher for all users*. This should install Python in - :file:`C:\\Program Files\\Python314-64`. In addition, *Add Python 3.14 to + :file:`C:\\Program Files\\Python315-64`. In addition, *Add Python 3.15 to PATH* should be activated so that this path to the Python installation is also entered in the list of ``PATH`` environment variables. #. Finally, you can now check the installation by entering the following in @@ -64,7 +64,7 @@ installed, this should not be a problem. .. code-block:: ps1con C:\> python -V - Python 3.14.0 + Python 3.15.0 .. warning:: One disadvantage is that you have to return to the website regularly to @@ -75,8 +75,8 @@ installed, this should not be a problem. If different Python versions are required, for example to test libraries with :doc:`test/tox`, I use :term:`uv`. This allows not only older CPython versions to be installed but also `PyPy `_ or free-threaded Python -3.14 with ``uv python install pypy@3.14`` or ``uv python install ---python-preference only-managed 3.14t``. +3.14 with ``uv python install pypy@3.15`` or ``uv python install +--python-preference only-managed 3.15t``. .. tip:: `direnv `_ allows you to set environment variables diff --git a/docs/packs/dataprep/pyproject.toml b/docs/packs/dataprep/pyproject.toml index 9bf086b8..1ec23693 100644 --- a/docs/packs/dataprep/pyproject.toml +++ b/docs/packs/dataprep/pyproject.toml @@ -10,15 +10,15 @@ readme = "README.rst" authors = [ { name = "Veit Schiele", email = "veit@cusy.io" }, ] -requires-python = ">=3.10" +requires-python = ">=3.11" classifiers = [ "Operating System :: OS Independent", "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: 3.15", ] dependencies = [ "cython", diff --git a/docs/test/libs/pytest/debug.rst b/docs/test/libs/pytest/debug.rst index 111c9c21..52f6c011 100644 --- a/docs/test/libs/pytest/debug.rst +++ b/docs/test/libs/pytest/debug.rst @@ -145,18 +145,18 @@ in our :file:`tox.ini` for cusy.tasks: [gh-actions] python = - 3.10: py310 3.11: py311 3.12: py312 3.13: py313 3.14: py314 + 3.15: py315 We want to run the Python 3.13 environment and start the debugger on a failed -test with ``tox -e py314 -- --pdb --no-cov``. This will take us to the pdb, +test with ``tox -e py315 -- --pdb --no-cov``. This will take us to the pdb, right at the assertion that failed. Once we have found and fixed the error, we can run the tox environment again -with this one test error: ``tox -e py314 -- --lf --tb=no --no-cov``. +with this one test error: ``tox -e py315 -- --lf --tb=no --no-cov``. Overview of the most common pytest debugger options --------------------------------------------------- diff --git a/pyproject.toml b/pyproject.toml index d26f22e0..ddb6c025 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,11 +8,10 @@ license-files = [ "LICENSE" ] authors = [ { name = "Veit Schiele", email = "veit@cusy.io" }, ] -requires-python = ">=3.10" +requires-python = ">=3.11" classifiers = [ "Operating System :: OS Independent", "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", From 0f28a5d0311ec60a9d9248d6efd2154207b7e886 Mon Sep 17 00:00:00 2001 From: veit Date: Sat, 24 Oct 2026 13:21:42 +0200 Subject: [PATCH 5/8] :pencil2: Fix tool.uv.exclude-newer-package --- docs/packs/apps.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/packs/apps.rst b/docs/packs/apps.rst index 429df465..21141adc 100644 --- a/docs/packs/apps.rst +++ b/docs/packs/apps.rst @@ -144,9 +144,9 @@ specific version. security vulnerabilities needs to be replaced with a more recent version as quickly as possible, the *dependency cooldowns* can be bypassed using - .. code-block:: console + .. code-block:: toml - $ uv sync --exclude-newer-package "{PACKAGE}=P0D" + exclude-newer-package = { PACKAGE = "P0D" } .. tip:: You can also use :doc:`Python4DataScience:productive/git/advanced/hooks/prek` From e9b93127ced270881c39a152d45a54bbd6eafe8a Mon Sep 17 00:00:00 2001 From: veit Date: Sat, 24 Oct 2026 13:50:12 +0200 Subject: [PATCH 6/8] :arrow_up: Update GH actions and prek checks --- .github/workflows/ci.yml | 2 +- .github/workflows/zizmor.yml | 2 +- .pre-commit-config.yaml | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9bf94fa8..26807355 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,7 +27,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: j178/prek-action@4e14d07f9231acabce116ccfca13b13dd9755ece # v3.0.0 + - uses: j178/prek-action@1382ad72dea72f9d53832f2bcb65b3e87a947204 # v3.0.1 docs: name: Build docs and check links diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml index 26d5335b..6c758b28 100644 --- a/.github/workflows/zizmor.yml +++ b/.github/workflows/zizmor.yml @@ -26,6 +26,6 @@ jobs: persist-credentials: false - name: Run zizmor - uses: zizmorcore/zizmor-action@cc914d7f3750a2d13d75c7f184a1060aa0e9d482 # v0.6.4 + uses: zizmorcore/zizmor-action@85b2b9fb8e3325e7a23d7d0a9d7ba5ae0f999e3e # v0.7.1 with: persona: pedantic diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 68298787..2fee4bed 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -15,7 +15,7 @@ repos: - id: check-added-large-files args: ['--maxkb=1024'] - repo: https://github.com/tox-dev/pyproject-fmt - rev: 59e7b26529dc6f15c43063064b8b06ded60d0910 # frozen: v2.29.4 + rev: 50e0f3aee9dc5747a5f173f79a7417403c18dda6 # frozen: v2.30.3 hooks: - id: pyproject-fmt - repo: https://github.com/abravalheri/validate-pyproject @@ -35,7 +35,7 @@ repos: entry: isort --profile=black name: isort (python) - repo: https://github.com/psf/black-pre-commit-mirror - rev: 4160603246a6b365d4a2af661c6d71b0a0f50478 # 26.5.1 + rev: a5439e9af2ff9371297bb1a76a01b8ad17989b88 # frozen: 26.10.1 hooks: - id: black - repo: https://github.com/adamchainz/blacken-docs From f4d59cb76a7c11f2513e7775be960073d46f22e1 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 18:57:58 +0000 Subject: [PATCH 7/8] [pre-commit.ci] pre-commit autoupdate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/pre-commit/pre-commit-hooks: 3e8a8703264a2f4a69428a0aa4dcb512790b2c8c → v6.0.0](https://github.com/pre-commit/pre-commit-hooks/compare/3e8a8703264a2f4a69428a0aa4dcb512790b2c8c...v6.0.0) - [github.com/abravalheri/validate-pyproject: 17e12779811926f000bdfa1795f9e3735dd71ac3 → 82d21874c3242e4dc27bb47641c996902ef64eef](https://github.com/abravalheri/validate-pyproject/compare/17e12779811926f000bdfa1795f9e3735dd71ac3...82d21874c3242e4dc27bb47641c996902ef64eef) - [github.com/sphinx-contrib/sphinx-lint: c883505f64b59c3c5c9375191e4ad9f98e727ccd → v1.0.2](https://github.com/sphinx-contrib/sphinx-lint/compare/c883505f64b59c3c5c9375191e4ad9f98e727ccd...v1.0.2) - [github.com/pycqa/isort: 9f905615631c545f5aea2516508109350d1d2f7d → 5d9c96196def28a1819b6a755a669ec0a3add6aa](https://github.com/pycqa/isort/compare/9f905615631c545f5aea2516508109350d1d2f7d...5d9c96196def28a1819b6a755a669ec0a3add6aa) - [github.com/adamchainz/blacken-docs: fda77690955e9b63c6687d8806bafd56a526e45f → 1.20.0](https://github.com/adamchainz/blacken-docs/compare/fda77690955e9b63c6687d8806bafd56a526e45f...1.20.0) --- .pre-commit-config.yaml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 2fee4bed..25ee1685 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -6,7 +6,7 @@ ci: repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: 3e8a8703264a2f4a69428a0aa4dcb512790b2c8c # v6.0.0 + rev: v6.0.0 # v6.0.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer @@ -19,16 +19,16 @@ repos: hooks: - id: pyproject-fmt - repo: https://github.com/abravalheri/validate-pyproject - rev: 17e12779811926f000bdfa1795f9e3735dd71ac3 # frozen: 0.26 + rev: 82d21874c3242e4dc27bb47641c996902ef64eef # frozen: v0.27 hooks: - id: validate-pyproject - repo: https://github.com/sphinx-contrib/sphinx-lint - rev: c883505f64b59c3c5c9375191e4ad9f98e727ccd # v1.0.2 + rev: v1.0.2 # v1.0.2 hooks: - id: sphinx-lint types: [rst] - repo: https://github.com/pycqa/isort - rev: 9f905615631c545f5aea2516508109350d1d2f7d # frozen: 9.0.2 + rev: 5d9c96196def28a1819b6a755a669ec0a3add6aa # frozen: 10.0.0b2 hooks: - id: isort additional_dependencies: ["toml"] @@ -39,7 +39,7 @@ repos: hooks: - id: black - repo: https://github.com/adamchainz/blacken-docs - rev: fda77690955e9b63c6687d8806bafd56a526e45f # 1.20.0 + rev: 1.20.0 # 1.20.0 hooks: - id: blacken-docs args: [--line-length=79] From cf38f5db2a3551e638311a99eceba05f69513b3c Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 19:00:59 +0000 Subject: [PATCH 8/8] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- docs/packs/myapp/pyproject.toml | 1 + docs/packs/mypack/pyproject.toml | 1 + docs/packs/pyproject.toml | 4 ++-- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/packs/myapp/pyproject.toml b/docs/packs/myapp/pyproject.toml index 681b307b..5371f1e6 100644 --- a/docs/packs/myapp/pyproject.toml +++ b/docs/packs/myapp/pyproject.toml @@ -15,6 +15,7 @@ classifiers = [ "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: 3.15", ] dependencies = [] scripts.myapp = "myapp:main" diff --git a/docs/packs/mypack/pyproject.toml b/docs/packs/mypack/pyproject.toml index eeb00be2..977cafaa 100644 --- a/docs/packs/mypack/pyproject.toml +++ b/docs/packs/mypack/pyproject.toml @@ -15,6 +15,7 @@ classifiers = [ "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: 3.15", ] dependencies = [] scripts.mypack = "mypack:main" diff --git a/docs/packs/pyproject.toml b/docs/packs/pyproject.toml index 0fc77403..b61c7212 100644 --- a/docs/packs/pyproject.toml +++ b/docs/packs/pyproject.toml @@ -1,7 +1,7 @@ [tool.cibuildwheel] -test-requires = "pytest" -test-command = "pytest {project}/tests" build-verbosity = 1 +test-command = "pytest {project}/tests" +test-requires = "pytest" # support Universal2 for Apple Silicon: macos.archs = [ "auto", "universal2" ] macos.test-skip = [ "*universal2:arm64" ]