@@ -111,17 +111,27 @@ def __repr__(self) -> str:
111111
112112@final
113113class MonkeyPatch :
114- """Object returned by the ``monkeypatch`` fixture keeping a record of
115- setattr/item/env/syspath changes."""
114+ """Helper to conveniently monkeypatch attributes/items/environment
115+ variables/syspath.
116+
117+ Returned by the :fixture:`monkeypatch` fixture.
118+
119+ :versionchanged:: 6.2
120+ Can now also be used directly as `pytest.MonkeyPatch()`, for when
121+ the fixture is not available. In this case, use
122+ :meth:`with MonkeyPatch.context() as mp: <context>` or remember to call
123+ :meth:`undo` explicitly.
124+ """
116125
117126 def __init__ (self ) -> None :
118127 self ._setattr : List [Tuple [object , str , object ]] = []
119128 self ._setitem : List [Tuple [MutableMapping [Any , Any ], object , object ]] = ([])
120129 self ._cwd : Optional [str ] = None
121130 self ._savesyspath : Optional [List [str ]] = None
122131
132+ @classmethod
123133 @contextmanager
124- def context (self ) -> Generator ["MonkeyPatch" , None , None ]:
134+ def context (cls ) -> Generator ["MonkeyPatch" , None , None ]:
125135 """Context manager that returns a new :class:`MonkeyPatch` object
126136 which undoes any patching done inside the ``with`` block upon exit.
127137
@@ -140,7 +150,7 @@ def test_partial(monkeypatch):
140150 such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples
141151 of this see `#3290 <https://github.com/pytest-dev/pytest/issues/3290>`_.
142152 """
143- m = MonkeyPatch ()
153+ m = cls ()
144154 try :
145155 yield m
146156 finally :
0 commit comments