Skip to content

Commit f92f61c

Browse files
committed
Fix the return type of django's from_field
from_field was annotated as returning SearchStrategy[F | None], where F is the type of the field passed in - i.e. a strategy for Field instances. It actually generates values for the field (e.g. strings for a CharField), so the correct annotation is SearchStrategy[Any].
1 parent 44b82b2 commit f92f61c

3 files changed

Lines changed: 25 additions & 3 deletions

File tree

‎hypothesis/RELEASE.rst‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
RELEASE_TYPE: patch
2+
3+
This patch fixes the type annotation of
4+
:func:`~hypothesis.extra.django.from_field`, which claimed to return a
5+
strategy for instances of the field type rather than for values of the field.

‎hypothesis/src/hypothesis/extra/django/_fields.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from datetime import datetime, timedelta
1515
from decimal import Decimal
1616
from functools import lru_cache
17-
from typing import Any, TypeAlias, TypeVar, Union
17+
from typing import Any, TypeAlias, Union
1818

1919
import django
2020
from django import forms as df
@@ -36,7 +36,6 @@
3636
# Use old-style union to avoid hitting
3737
# https://github.com/sphinx-doc/sphinx/issues/11211
3838
AnyField: TypeAlias = Union[dm.Field, df.Field] # noqa: UP007
39-
F = TypeVar("F", bound=AnyField)
4039

4140

4241
def numeric_bounds_from_validators(
@@ -360,7 +359,7 @@ def register_field_strategy(
360359
_global_field_lookup[field_type] = strategy
361360

362361

363-
def from_field(field: F) -> st.SearchStrategy[F | None]:
362+
def from_field(field: AnyField) -> st.SearchStrategy[Any]:
364363
"""Return a strategy for values that fit the given field.
365364
366365
This function is used by :func:`~hypothesis.extra.django.from_form` and

‎whole_repo_tests/types/test_pyright.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,24 @@ def test_pandas_column(tmp_path, val, expect):
282282
assert typ == f"column[{expect}]"
283283

284284

285+
def test_django_from_field(tmp_path):
286+
f = tmp_path / "test.py"
287+
f.write_text(
288+
textwrap.dedent("""
289+
from django import forms
290+
from hypothesis.extra.django import from_field
291+
292+
x = from_field(forms.CharField())
293+
reveal_type(x)
294+
"""),
295+
encoding="utf-8",
296+
)
297+
_write_config(
298+
tmp_path, {"typeCheckingMode": "strict", "reportMissingTypeStubs": "none"}
299+
)
300+
assert get_pyright_analysed_type(f) == "SearchStrategy[Any]"
301+
302+
285303
def test_pyright_tuples_pos_args_only(tmp_path: Path):
286304
file = tmp_path / "test.py"
287305
file.write_text(

0 commit comments

Comments
 (0)