Skip to content
Open
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
14 changes: 13 additions & 1 deletion rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import inspect
import math
import re
import sys
import uuid
import warnings
from collections.abc import Mapping
Expand Down Expand Up @@ -58,6 +59,17 @@ class BuiltinSignatureError(Exception):
pass


if sys.version_info >= (3, 14):
# Annotations are evaluated lazily since Python 3.14 (PEP 649), and
# inspect.signature() evaluates them, raising NameError for names only
# imported under TYPE_CHECKING. Only parameter kinds and defaults are
# needed in is_simple_callable(). See https://github.com/encode/django-rest-framework/discussions/9959
import annotationlib
SIGNATURE_KWARGS = {'annotation_format': annotationlib.Format.FORWARDREF}
else:
SIGNATURE_KWARGS = {}


def is_simple_callable(obj):
"""
True if the object is a callable that takes no arguments.
Expand All @@ -74,7 +86,7 @@ def is_simple_callable(obj):
if not (inspect.isfunction(obj) or inspect.ismethod(obj) or isinstance(obj, functools.partial)):
return False

sig = inspect.signature(obj)
sig = inspect.signature(obj, **SIGNATURE_KWARGS)
params = sig.parameters.values()
return all(
param.kind == param.VAR_POSITIONAL or
Expand Down
18 changes: 18 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import math
import os
import re
import sys
import uuid
import warnings
from decimal import ROUND_DOWN, ROUND_UP, Decimal
Expand Down Expand Up @@ -121,6 +122,23 @@ def test_type_annotation(self):

assert is_simple_callable(valid)

@pytest.mark.skipif(sys.version_info < (3, 14), reason="Annotations are evaluated lazily from Python 3.14")
def test_unresolvable_type_annotation(self):
# A name only imported under `if TYPE_CHECKING:` is undefined at runtime.
class Foo:
def valid(self) -> UndefinedType: # noqa: F821
pass

def valid(param: UndefinedType = None): # noqa: F821
pass

def invalid(param: UndefinedType): # noqa: F821
pass

assert is_simple_callable(Foo().valid)
Comment thread
browniebroke marked this conversation as resolved.
assert is_simple_callable(valid)
assert not is_simple_callable(invalid)


# Tests for field keyword arguments and core functionality.
# ---------------------------------------------------------
Expand Down
Loading