From 182983fb9a2736ba177c5e89e3c8b5a7d5d70453 Mon Sep 17 00:00:00 2001 From: mukunda katta Date: Fri, 15 May 2026 13:20:15 -0700 Subject: [PATCH] docs: clarify stdlib monkeypatch guidance --- changelog/11022.doc.rst | 1 + doc/en/how-to/monkeypatch.rst | 9 ++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 changelog/11022.doc.rst diff --git a/changelog/11022.doc.rst b/changelog/11022.doc.rst new file mode 100644 index 00000000000..45f08aeec4f --- /dev/null +++ b/changelog/11022.doc.rst @@ -0,0 +1 @@ +Document safer alternatives and scope guidance for monkeypatching standard library functions. diff --git a/doc/en/how-to/monkeypatch.rst b/doc/en/how-to/monkeypatch.rst index 7442a85c10e..642e965b618 100644 --- a/doc/en/how-to/monkeypatch.rst +++ b/doc/en/how-to/monkeypatch.rst @@ -241,7 +241,14 @@ so that any attempts within tests to create http requests will fail. .. note:: Mind that patching ``stdlib`` functions and some third-party libraries used by pytest - might break pytest itself, therefore in those cases it is recommended to use + might break pytest itself. Prefer patching the reference that your code uses + instead of patching the original object in the standard library. For example, + if your module does ``from os import getcwd``, patch ``mymodule.getcwd`` + rather than ``os.getcwd``. + + For code that you control, a safer long-term pattern is to make dependencies + explicit so they can be passed into the code under test instead of patched + globally. When patching a stdlib object is unavoidable, use :meth:`MonkeyPatch.context` to limit the patching to the block you want tested: .. code-block:: python