Backtestspytestrun-20261106-234554#13354

Issue #13354 Merged fix PR #14833 Run 6 Nov 2026 · run-20261106-234554 pytest-dev/pytest

Node.get_closest_marker default kwarg deprecation

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

The reported problem is that the only way to satisfy the `default: Mark` parameter is to build a `pytest.Mark`, which now warns. At runtime `next(iter, default)` already accepts anything, so the real restriction is the type signature. Patch B fixes that at the root: the overload becomes `default: _T -> Mark | _T`, so any sentinel (or `pytest.mark.x(...).mark`) is a valid, correctly typed fallback, matching the conventional `dict.get`-style contract. It adds `typing_checks.py` assertions that pin the new overload behaviour (the right place for a typing fix), a functional test covering sentinel/None/`.mark` defaults, and a `-W error::PytestDeprecationWarning` test showing the documented alternative is warning-free. The docstring explicitly tells users to use `pytest.mark.<name>(...).mark`, which is the missing 'alternative way' the issue asks for. Patch A instead adds a special case: it accepts a `MarkDecorator` and silently unwraps it. That is a reasonable convenience and its test does fail-before/pass-after, but it keeps the `default` type artificially restricted to Mark-like values (the independent sentinel test still fails with A), adds an isinstance branch to a hot accessor, and does not point users at the already-working `.mark` route. The independent tests split (A passes the decorator-default test, B passes the sentinel test); the issue only asks for an alternative way to pass a default, which B provides generally while A provides narrowly. Minor nit on B: the implementation signature widens to `object -> object`, but the public overloads carry the precise types. Overall B is the more complete and conventional fix with better type-level test coverage.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

6m 12s

Wall-clock time in the container

Full test suite

No new failures

515 passed · 18 skipped · 550 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

77vs 29 merged

Changed lines, ours vs merged

I passed pytest.Mark as a default. Now we have deprecation warning and no alternative to pass default to Node.get_closest_marker.

I think that overload of Node.get_closest_marker with default kwarg should be deprecated or we should have alternative way to pass default.

commit, where deprecation warning of pytest.Mark.__init__ was added: https://github.com/pytest-dev/pytest/commit/2ec372df8b987207efc4ad0f33c2f82df5c9e2e5

The two patches

Our patch+74 −3
changelog/13354.improvement.rstnew file mode 100644index 000000000..3e77d4d33@@ -0,0 +1 @@+:meth:`Node.get_closest_marker <_pytest.nodes.Node.get_closest_marker>` now accepts a ``default`` of any type, not only :class:`pytest.Mark` -- since constructing :class:`pytest.Mark` directly is deprecated, use any sentinel value or ``pytest.mark.<name>(...).mark`` as the fallback instead.src/_pytest/nodes.pyindex f0629c2da..e7b92ad9d 100644@@ -352,14 +352,19 @@ class Node(abc.ABC, metaclass=NodeMeta):     def get_closest_marker(self, name: str) -> Mark | None: ...      @overload-    def get_closest_marker(self, name: str, default: Mark) -> Mark: ...+    def get_closest_marker(self, name: str, default: _T) -> Mark | _T: ... -    def get_closest_marker(self, name: str, default: Mark | None = None) -> Mark | None:+    def get_closest_marker(self, name: str, default: object = None) -> object:         """Return the first marker matching the name, from closest (for         example function) to farther level (for example module level). -        :param default: Fallback return value if no marker was found.         :param name: Name to filter by.+        :param default:+            Fallback return value if no marker was found.+            This can be any object, it does not need to be a :class:`pytest.Mark`+            (which should not be instantiated directly).+            If a default :class:`pytest.Mark` is really needed, use+            ``pytest.mark.<name>(...).mark``.         """         return next(self.iter_markers(name=name), default) testing/test_mark.pyindex 2e105dfe4..5b5405b08 100644@@ -772,6 +772,64 @@ class TestFunctional:         assert has_inherited_marker.kwargs == {"location": "class"}         assert has_own.get_closest_marker("missing") is None +    def test_get_closest_marker_default(self, pytester: Pytester) -> None:+        """A non-Mark default can be passed without constructing a Mark (#13354)."""+        p = pytester.makepyfile(+            """+            import pytest++            @pytest.mark.c(location="function")+            def test_has_own():+                pass+        """+        )+        items, _rec = pytester.inline_genitems(p)+        (item,) = items+        sentinel = object()+        assert item.get_closest_marker("missing", sentinel) is sentinel+        assert item.get_closest_marker("missing", default=sentinel) is sentinel+        assert item.get_closest_marker("missing", default=None) is None+        own = item.get_closest_marker("c", default=sentinel)+        assert isinstance(own, pytest.Mark)+        assert own.kwargs == {"location": "function"}++        default_mark = pytest.mark.skip(reason="default").mark+        found = item.get_closest_marker("skip", default=default_mark)+        assert found is default_mark+        assert found.name == "skip"+        assert found.kwargs == {"reason": "default"}++    def test_get_closest_marker_default_no_deprecation_warning(+        self, pytester: Pytester+    ) -> None:+        """Passing a default does not require deprecated Mark construction (#13354)."""+        pytester.makeconftest(+            """+            import pytest++            @pytest.fixture+            def timeout(request):+                marker = request.node.get_closest_marker(+                    "timeout", default=pytest.mark.timeout(5).mark+                )+                return marker.args[0]+        """+        )+        pytester.makepyfile(+            """+            import pytest++            def test_default(timeout):+                assert timeout == 5++            @pytest.mark.timeout(10)+            def test_marked(timeout):+                assert timeout == 10+        """+        )+        result = pytester.runpytest("-W", "error::pytest.PytestDeprecationWarning")+        result.assert_outcomes(passed=2)+     def test_mark_with_wrong_marker(self, pytester: Pytester) -> None:         reprec = pytester.inline_runsource(             """testing/typing_checks.pyindex 1179f3f5d..e22624565 100644@@ -74,6 +74,13 @@ def check_scope_typing() -> None:     assert_type(custom_scope, ScopeName)  +# Issue #13354.+def check_get_closest_marker_default(item: pytest.Item) -> None:+    assert_type(item.get_closest_marker("foo"), pytest.Mark | None)+    assert_type(item.get_closest_marker("foo", default=None), pytest.Mark | None)+    assert_type(item.get_closest_marker("foo", 0), pytest.Mark | int)++ # Issue #14606. @pytest.mark.parametrize("x", [ImportError, AttributeError]) def check_mypy_bug_with_argvalues(x) -> None: 
Merged fix · PR #14833+26 −3
AUTHORSindex 19c4451cf..47e310c23 100644@@ -7,6 +7,7 @@ Aaron Coleman Abdeali JK Abdelrahman Elbehery Abhijeet Kasurde+ace2016 Adam Johnson Adam Stewart Adam Uhlirchangelog/13354.improvement.rstnew file mode 100644index 000000000..9b90b284c@@ -0,0 +1,3 @@+:meth:`Node.get_closest_marker <_pytest.nodes.Node.get_closest_marker>` now also accepts a :class:`~pytest.MarkDecorator` as its ``default``, for example ``item.get_closest_marker("foo", pytest.mark.foo(1))``, and returns the wrapped :class:`~pytest.Mark`.++Previously the only way to build a ``default`` was to instantiate :class:`~pytest.Mark` directly, which is private and warns.src/_pytest/nodes.pyindex f0629c2da..c6d245de6 100644@@ -352,15 +352,22 @@ class Node(abc.ABC, metaclass=NodeMeta):     def get_closest_marker(self, name: str) -> Mark | None: ...      @overload-    def get_closest_marker(self, name: str, default: Mark) -> Mark: ...+    def get_closest_marker(self, name: str, default: Mark | MarkDecorator) -> Mark: ... -    def get_closest_marker(self, name: str, default: Mark | None = None) -> Mark | None:+    def get_closest_marker(+        self, name: str, default: Mark | MarkDecorator | None = None+    ) -> Mark | None:         """Return the first marker matching the name, from closest (for         example function) to farther level (for example module level). -        :param default: Fallback return value if no marker was found.+        :param default:+            Fallback return value if no marker was found. A+            :class:`~pytest.MarkDecorator` such as ``pytest.mark.foo(1)`` is+            also accepted, in which case its :class:`~pytest.Mark` is returned.         :param name: Name to filter by.         """+        if isinstance(default, MarkDecorator):+            default = default.mark         return next(self.iter_markers(name=name), default)      def listextrakeywords(self) -> set[str]:testing/test_mark.pyindex 2e105dfe4..9b0cc44d2 100644@@ -772,6 +772,18 @@ class TestFunctional:         assert has_inherited_marker.kwargs == {"location": "class"}         assert has_own.get_closest_marker("missing") is None +    def test_mark_closest_default_mark_decorator(self, pytester: Pytester) -> None:+        p = pytester.makepyfile(+            """+            def test_without_mark():+                pass+        """+        )+        items, _rec = pytester.inline_genitems(p)+        (item,) = items+        default = pytest.mark.foo(location="default")+        assert item.get_closest_marker("foo", default) is default.mark+     def test_mark_with_wrong_marker(self, pytester: Pytester) -> None:         reprec = pytester.inline_runsource(             """