Skip to content

Defer annotation eval on Python 3.14 #13550

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog/13549.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
No longer evaluate type annotations in Python ``3.14`` when inspecting function signatures.

This prevents crashes during module collection when modules do not explicitly use ``from __future__ import annotations`` and import types for annotations within a ``if TYPE_CHECKING:`` block.
13 changes: 12 additions & 1 deletion src/_pytest/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import functools
import inspect
from inspect import Parameter
from inspect import signature
from inspect import Signature
import os
from pathlib import Path
import sys
Expand All @@ -19,6 +19,10 @@
import py


if sys.version_info >= (3, 14):
from annotationlib import Format


#: constant to prepare valuing pylib path replacements/lazy proxies later on
# intended for removal in pytest 8.0 or 9.0

Expand Down Expand Up @@ -60,6 +64,13 @@ def is_async_function(func: object) -> bool:
return iscoroutinefunction(func) or inspect.isasyncgenfunction(func)


def signature(obj: Callable[..., Any]) -> Signature:
"""Return signature without evaluating annotations."""
if sys.version_info >= (3, 14):
return inspect.signature(obj, annotation_format=Format.STRING)
return inspect.signature(obj)


def getlocation(function, curdir: str | os.PathLike[str] | None = None) -> str:
function = get_real_func(function)
fn = Path(inspect.getfile(function))
Expand Down
5 changes: 3 additions & 2 deletions src/_pytest/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
from _pytest.compat import NotSetType
from _pytest.compat import safe_getattr
from _pytest.compat import safe_isclass
from _pytest.compat import signature
from _pytest.config import _PluggyPlugin
from _pytest.config import Config
from _pytest.config import ExitCode
Expand Down Expand Up @@ -804,8 +805,8 @@ def _format_fixturedef_line(self, fixturedef: FixtureDef[object]) -> str:
path, lineno = getfslineno(factory)
if isinstance(path, Path):
path = bestrelpath(self._pyfuncitem.session.path, path)
signature = inspect.signature(factory)
return f"{path}:{lineno + 1}: def {factory.__name__}{signature}"
sig = signature(factory)
return f"{path}:{lineno + 1}: def {factory.__name__}{sig}"

def addfinalizer(self, finalizer: Callable[[], object]) -> None:
self._fixturedef.addfinalizer(finalizer)
Expand Down
2 changes: 1 addition & 1 deletion src/_pytest/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from collections.abc import MutableMapping
from functools import cached_property
from functools import lru_cache
from inspect import signature
import os
import pathlib
from pathlib import Path
Expand All @@ -29,6 +28,7 @@
from _pytest._code.code import Traceback
from _pytest._code.code import TracebackStyle
from _pytest.compat import LEGACY_PATH
from _pytest.compat import signature
from _pytest.config import Config
from _pytest.config import ConftestImportFailure
from _pytest.config.compat import _check_path
Expand Down
40 changes: 40 additions & 0 deletions testing/test_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -1895,3 +1895,43 @@ def test_with_yield():
)
# Assert that no tests were collected
result.stdout.fnmatch_lines(["*collected 0 items*"])


def test_annotations_deferred_future(pytester: Pytester):
"""Ensure stringified annotations don't raise any errors."""
pytester.makepyfile(
"""
from __future__ import annotations
import pytest

@pytest.fixture
def func() -> X: ... # X is undefined

def test_func():
assert True
"""
)
result = pytester.runpytest()
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 passed*"])


@pytest.mark.skipif(
sys.version_info < (3, 14), reason="Annotations are only skipped on 3.14+"
)
def test_annotations_deferred_314(pytester: Pytester):
"""Ensure annotation eval is deferred."""
pytester.makepyfile(
"""
import pytest

@pytest.fixture
def func() -> X: ... # X is undefined

def test_func():
assert True
"""
)
result = pytester.runpytest()
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 passed*"])