Skip to content

Commit

Permalink
Improve handling of fwd-reference in get_type_hints. Closes #3519
Browse files Browse the repository at this point in the history
  • Loading branch information
rsokl committed Dec 3, 2022
1 parent 808c61b commit 490f4c9
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
6 changes: 6 additions & 0 deletions hypothesis-python/RELEASE.rst
@@ -0,0 +1,6 @@
RELEASE_TYPE: minor

This release improves Hypothesis' ability to resolve forward references in
type annotations. It fixes a bug that prevented
:func:`~hypothesis.strategies.builds` from being used with `pydantic models that
possess updated forward references <https://pydantic-docs.helpmanual.io/usage/postponed_annotations/>`__. See :issue:`3519`.
7 changes: 6 additions & 1 deletion hypothesis-python/src/hypothesis/internal/compat.py
Expand Up @@ -111,8 +111,13 @@ def get_type_hints(thing):
and is_a_type(p.annotation)
and p.annotation is not p.empty
):
if isinstance(p.annotation, typing.ForwardRef) and not isinstance(
hints[p.name], typing.ForwardRef
):
continue

if p.default is None:
hints[p.name] = typing.Optional[p.annotation]
hints[p.name] = typing.Optional[p.annotation] # type: ignore
else:
hints[p.name] = p.annotation
except (AttributeError, TypeError, NameError): # pragma: no cover
Expand Down
25 changes: 24 additions & 1 deletion hypothesis-python/tests/cover/test_compat.py
Expand Up @@ -9,7 +9,9 @@
# obtain one at https://mozilla.org/MPL/2.0/.

import math
from inspect import Parameter, Signature
from dataclasses import dataclass
from inspect import Parameter, Signature, signature
from typing import ForwardRef

import pytest

Expand Down Expand Up @@ -45,3 +47,24 @@ class WeirdSig:

def test_no_type_hints():
assert get_type_hints(WeirdSig) == {}


@dataclass
class Foo:
x: "Foo"


Foo.__signature__ = signature(Foo).replace( # type: ignore
parameters=[
Parameter(
"x",
Parameter.POSITIONAL_OR_KEYWORD,
annotation=ForwardRef("Foo"),
)
]
)


def test_resolve_fwd_refs():
# See: https://github.com/HypothesisWorks/hypothesis/issues/3519
assert get_type_hints(Foo)["x"] is Foo

0 comments on commit 490f4c9

Please sign in to comment.