We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
from_type() does not resolve forward references outside of function annotations
The sample code:
```python
import typing as T

import hypothesis as H
import hypothesis.strategies as S

class Tree(T.NamedTuple):
    val: int
    l: T.Optional["Tree"]
    r: T.Optional["Tree"]
    def size(self):
        return 1 + (self.l.size() if self.l else 0) + (self.r.size() if self.r else 0)

@H.given(t = S.infer)
def test_tree(t: Tree):
    if t.size() > 3:
        assert False
        H.note(t)
    else:
        assert True
```

(Part of) the stack trace:
```
platform darwin -- Python 3.6.1, pytest-3.2.1, py-1.4.34, pluggy-0.4.0
rootdir: /Users/desmond/Documents/code/code-python/Try1/tests, inifile:
plugins: xonsh-0.5.12, hypothesis-3.38.9
collected 4 items
foo_test.py ...F
foo_test.py:36 (test_tree)
args = (<class 'foo_test.Tree'>,), kwargs = {}, kwargs_cache_key = set()
cache_key = (<function from_type at 0x112216a60>, ((<class 'type'>, <class 'foo_test.Tree'>),), frozenset())
result = builds(Tree, l=builds(lazy_error), r=builds(lazy_error), val=integers())

    @proxies(fn)
    def cached_strategy(*args, **kwargs):
        kwargs_cache_key = set()
        try:
            for k, v in kwargs.items():
                kwargs_cache_key.add((k, convert_value(v)))
        except TypeError:
            return fn(*args, **kwargs)
        cache_key = (
            fn,
            tuple(map(convert_value, args)), frozenset(kwargs_cache_key))
        try:
>           return STRATEGY_CACHE[cache_key]

/Users/desmond/anaconda3/lib/python3.6/site-packages/hypothesis/strategies.py:107: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = {(<function booleans at 0x112763e18>, (), frozenset()): booleans(), (<function fractions at 0x112216d90>, ((<class 'No...(tuples(), fixed_dictionaries({})).map(lambda value: target(*value[0], **value[1])),
 'val': WideRangeIntStrategy()}))}
key = (<function from_type at 0x112216a60>, ((<class 'type'>, <class 'foo_test.Tree'>),), frozenset())

    def __getitem__(self, key):
>       i = self.keys_to_indices[key]
E       KeyError: (<function from_type at 0x112216a60>, ((<class 'type'>, <class 'foo_test.Tree'>),), frozenset())

```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `hypothesis-python/src/hypothesis/internal/compat.py`
Content:
```
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Most of this work is copyright (C) 2013-2020 David R. MacIver
5 # (david@drmaciver.com), but it contains contributions by others. See
6 # CONTRIBUTING.rst for a full list of people who may hold copyright, and
7 # consult the git log if you need to determine who owns an individual
8 # contribution.
9 #
10 # This Source Code Form is subject to the terms of the Mozilla Public License,
11 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
12 # obtain one at https://mozilla.org/MPL/2.0/.
13 #
14 # END HEADER
15 
16 import codecs
17 import importlib
18 import inspect
19 import platform
20 import sys
21 import time
22 import typing
23 
24 PYPY = platform.python_implementation() == "PyPy"
25 CAN_PACK_HALF_FLOAT = sys.version_info[:2] >= (3, 6)
26 WINDOWS = platform.system() == "Windows"
27 
28 
29 def bit_length(n):
30     return n.bit_length()
31 
32 
33 def str_to_bytes(s):
34     return s.encode(a_good_encoding())
35 
36 
37 def escape_unicode_characters(s):
38     return codecs.encode(s, "unicode_escape").decode("ascii")
39 
40 
41 def int_from_bytes(data):
42     return int.from_bytes(data, "big")
43 
44 
45 def int_to_bytes(i, size):
46     return i.to_bytes(size, "big")
47 
48 
49 def int_to_byte(i):
50     return bytes([i])
51 
52 
53 def benchmark_time():
54     return time.monotonic()
55 
56 
57 def a_good_encoding():
58     return "utf-8"
59 
60 
61 def to_unicode(x):
62     if isinstance(x, str):
63         return x
64     else:
65         return x.decode(a_good_encoding())
66 
67 
68 def qualname(f):
69     try:
70         return f.__qualname__
71     except AttributeError:
72         return f.__name__
73 
74 
75 try:
76     # These types are new in Python 3.7, but also (partially) backported to the
77     # typing backport on PyPI.  Use if possible; or fall back to older names.
78     typing_root_type = (typing._Final, typing._GenericAlias)  # type: ignore
79     ForwardRef = typing.ForwardRef  # type: ignore
80 except AttributeError:
81     typing_root_type = (typing.TypingMeta, typing.TypeVar)  # type: ignore
82     try:
83         typing_root_type += (typing._Union,)  # type: ignore
84     except AttributeError:
85         pass
86     ForwardRef = typing._ForwardRef  # type: ignore
87 
88 
89 def is_typed_named_tuple(cls):
90     """Return True if cls is probably a subtype of `typing.NamedTuple`.
91 
92     Unfortunately types created with `class T(NamedTuple):` actually
93     subclass `tuple` directly rather than NamedTuple.  This is annoying,
94     and means we just have to hope that nobody defines a different tuple
95     subclass with similar attributes.
96     """
97     return (
98         issubclass(cls, tuple)
99         and hasattr(cls, "_fields")
100         and hasattr(cls, "_field_types")
101     )
102 
103 
104 if sys.version_info[:2] < (3, 6):
105     # When we drop support for Python 3.5, `get_type_hints` and
106     # `is_typed_named_tuple` should be moved to reflection.py
107 
108     def get_type_hints(thing):
109         if inspect.isclass(thing) and not hasattr(thing, "__signature__"):
110             if is_typed_named_tuple(thing):
111                 # Special handling for typing.NamedTuple
112                 return thing._field_types  # type: ignore
113             thing = thing.__init__  # type: ignore
114         try:
115             spec = inspect.getfullargspec(thing)
116             return {
117                 k: v
118                 for k, v in spec.annotations.items()
119                 if k in (spec.args + spec.kwonlyargs) and isinstance(v, type)
120             }
121         except TypeError:
122             return {}
123 
124 
125 else:
126 
127     def get_type_hints(thing):
128         if inspect.isclass(thing) and not hasattr(thing, "__signature__"):
129             if is_typed_named_tuple(thing):
130                 # Special handling for typing.NamedTuple
131                 return thing._field_types  # type: ignore
132             thing = thing.__init__  # type: ignore
133         try:
134             return typing.get_type_hints(thing)
135         except TypeError:
136             return {}
137 
138 
139 importlib_invalidate_caches = getattr(importlib, "invalidate_caches", lambda: ())
140 
141 
142 def update_code_location(code, newfile, newlineno):
143     """Take a code object and lie shamelessly about where it comes from.
144 
145     Why do we want to do this? It's for really shallow reasons involving
146     hiding the hypothesis_temporary_module code from test runners like
147     pytest's verbose mode. This is a vastly disproportionate terrible
148     hack that I've done purely for vanity, and if you're reading this
149     code you're probably here because it's broken something and now
150     you're angry at me. Sorry.
151     """
152     if hasattr(code, "replace"):
153         # Python 3.8 added positional-only params (PEP 570), and thus changed
154         # the layout of code objects.  In beta1, the `.replace()` method was
155         # added to facilitate future-proof code.  See BPO-37032 for details.
156         return code.replace(co_filename=newfile, co_firstlineno=newlineno)
157 
158     # This field order is accurate for 3.5 - 3.7, but not 3.8 when a new field
159     # was added for positional-only arguments.  However it also added a .replace()
160     # method that we use instead of field indices, so they're fine as-is.
161     CODE_FIELD_ORDER = [
162         "co_argcount",
163         "co_kwonlyargcount",
164         "co_nlocals",
165         "co_stacksize",
166         "co_flags",
167         "co_code",
168         "co_consts",
169         "co_names",
170         "co_varnames",
171         "co_filename",
172         "co_name",
173         "co_firstlineno",
174         "co_lnotab",
175         "co_freevars",
176         "co_cellvars",
177     ]
178     unpacked = [getattr(code, name) for name in CODE_FIELD_ORDER]
179     unpacked[CODE_FIELD_ORDER.index("co_filename")] = newfile
180     unpacked[CODE_FIELD_ORDER.index("co_firstlineno")] = newlineno
181     return type(code)(*unpacked)
182 
183 
184 def cast_unicode(s, encoding=None):
185     if isinstance(s, bytes):
186         return s.decode(encoding or a_good_encoding(), "replace")
187     return s
188 
189 
190 def get_stream_enc(stream, default=None):
191     return getattr(stream, "encoding", None) or default
192 
193 
194 # Under Python 2, math.floor and math.ceil return floats, which cannot
195 # represent large integers - eg `float(2**53) == float(2**53 + 1)`.
196 # We therefore implement them entirely in (long) integer operations.
197 # We use the same trick on Python 3, because Numpy values and other
198 # custom __floor__ or __ceil__ methods may convert via floats.
199 # See issue #1667, Numpy issue 9068.
200 def floor(x):
201     y = int(x)
202     if y != x and x < 0:
203         return y - 1
204     return y
205 
206 
207 def ceil(x):
208     y = int(x)
209     if y != x and x > 0:
210         return y + 1
211     return y
212 
213 
214 try:
215     from django.test import TransactionTestCase
216 
217     def bad_django_TestCase(runner):
218         if runner is None:
219             return False
220         if not isinstance(runner, TransactionTestCase):
221             return False
222 
223         from hypothesis.extra.django._impl import HypothesisTestCase
224 
225         return not isinstance(runner, HypothesisTestCase)
226 
227 
228 except Exception:
229     # Can't use ImportError, because of e.g. Django config errors
230     def bad_django_TestCase(runner):
231         return False
232
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/hypothesis-python/src/hypothesis/internal/compat.py b/hypothesis-python/src/hypothesis/internal/compat.py
--- a/hypothesis-python/src/hypothesis/internal/compat.py
+++ b/hypothesis-python/src/hypothesis/internal/compat.py
@@ -125,14 +125,25 @@
 else:
 
     def get_type_hints(thing):
-        if inspect.isclass(thing) and not hasattr(thing, "__signature__"):
-            if is_typed_named_tuple(thing):
-                # Special handling for typing.NamedTuple
-                return thing._field_types  # type: ignore
-            thing = thing.__init__  # type: ignore
+        """Like the typing version, but tries harder and never errors.
+
+        Tries harder: if the thing to inspect is a class but typing.get_type_hints
+        raises an error or returns no hints, then this function will try calling it
+        on the __init__ method.  This second step often helps with user-defined
+        classes on older versions of Python.
+
+        Never errors: instead of raising TypeError for uninspectable objects, or
+        NameError for unresolvable forward references, just return an empty dict.
+        """
         try:
-            return typing.get_type_hints(thing)
-        except TypeError:
+            hints = typing.get_type_hints(thing)
+        except (TypeError, NameError):
+            hints = {}
+        if hints or not inspect.isclass(thing):
+            return hints
+        try:
+            return typing.get_type_hints(thing.__init__)
+        except (TypeError, NameError, AttributeError):
             return {}

{"golden_diff": "diff --git a/hypothesis-python/src/hypothesis/internal/compat.py b/hypothesis-python/src/hypothesis/internal/compat.py\n--- a/hypothesis-python/src/hypothesis/internal/compat.py\n+++ b/hypothesis-python/src/hypothesis/internal/compat.py\n@@ -125,14 +125,25 @@\n else:\n \n     def get_type_hints(thing):\n-        if inspect.isclass(thing) and not hasattr(thing, \"__signature__\"):\n-            if is_typed_named_tuple(thing):\n-                # Special handling for typing.NamedTuple\n-                return thing._field_types  # type: ignore\n-            thing = thing.__init__  # type: ignore\n+        \"\"\"Like the typing version, but tries harder and never errors.\n+\n+        Tries harder: if the thing to inspect is a class but typing.get_type_hints\n+        raises an error or returns no hints, then this function will try calling it\n+        on the __init__ method.  This second step often helps with user-defined\n+        classes on older versions of Python.\n+\n+        Never errors: instead of raising TypeError for uninspectable objects, or\n+        NameError for unresolvable forward references, just return an empty dict.\n+        \"\"\"\n         try:\n-            return typing.get_type_hints(thing)\n-        except TypeError:\n+            hints = typing.get_type_hints(thing)\n+        except (TypeError, NameError):\n+            hints = {}\n+        if hints or not inspect.isclass(thing):\n+            return hints\n+        try:\n+            return typing.get_type_hints(thing.__init__)\n+        except (TypeError, NameError, AttributeError):\n             return {}\n", "issue": "from_type() does not resolve forward references outside of function annotations\nThe sample code:\r\n```python\r\nimport typing as T\r\n\r\nimport hypothesis as H\r\nimport hypothesis.strategies as S\r\n\r\nclass Tree(T.NamedTuple):\r\n    val: int\r\n    l: T.Optional[\"Tree\"]\r\n    r: T.Optional[\"Tree\"]\r\n    def size(self):\r\n        return 1 + (self.l.size() if self.l else 0) + (self.r.size() if self.r else 0)\r\n\r\n@H.given(t = S.infer)\r\ndef test_tree(t: Tree):\r\n    if t.size() > 3:\r\n        assert False\r\n        H.note(t)\r\n    else:\r\n        assert True\r\n```\r\n\r\n(Part of) the stack trace:\r\n```\r\nplatform darwin -- Python 3.6.1, pytest-3.2.1, py-1.4.34, pluggy-0.4.0\r\nrootdir: /Users/desmond/Documents/code/code-python/Try1/tests, inifile:\r\nplugins: xonsh-0.5.12, hypothesis-3.38.9\r\ncollected 4 items\r\nfoo_test.py ...F\r\nfoo_test.py:36 (test_tree)\r\nargs = (<class 'foo_test.Tree'>,), kwargs = {}, kwargs_cache_key = set()\r\ncache_key = (<function from_type at 0x112216a60>, ((<class 'type'>, <class 'foo_test.Tree'>),), frozenset())\r\nresult = builds(Tree, l=builds(lazy_error), r=builds(lazy_error), val=integers())\r\n\r\n    @proxies(fn)\r\n    def cached_strategy(*args, **kwargs):\r\n        kwargs_cache_key = set()\r\n        try:\r\n            for k, v in kwargs.items():\r\n                kwargs_cache_key.add((k, convert_value(v)))\r\n        except TypeError:\r\n            return fn(*args, **kwargs)\r\n        cache_key = (\r\n            fn,\r\n            tuple(map(convert_value, args)), frozenset(kwargs_cache_key))\r\n        try:\r\n>           return STRATEGY_CACHE[cache_key]\r\n\r\n/Users/desmond/anaconda3/lib/python3.6/site-packages/hypothesis/strategies.py:107: \r\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \r\n\r\nself = {(<function booleans at 0x112763e18>, (), frozenset()): booleans(), (<function fractions at 0x112216d90>, ((<class 'No...(tuples(), fixed_dictionaries({})).map(lambda value: target(*value[0], **value[1])),\r\n 'val': WideRangeIntStrategy()}))}\r\nkey = (<function from_type at 0x112216a60>, ((<class 'type'>, <class 'foo_test.Tree'>),), frozenset())\r\n\r\n    def __getitem__(self, key):\r\n>       i = self.keys_to_indices[key]\r\nE       KeyError: (<function from_type at 0x112216a60>, ((<class 'type'>, <class 'foo_test.Tree'>),), frozenset())\r\n\r\n```\n", "before_files": [{"content": "# This file is part of Hypothesis, which may be found at\n# https://github.com/HypothesisWorks/hypothesis/\n#\n# Most of this work is copyright (C) 2013-2020 David R. MacIver\n# (david@drmaciver.com), but it contains contributions by others. See\n# CONTRIBUTING.rst for a full list of people who may hold copyright, and\n# consult the git log if you need to determine who owns an individual\n# contribution.\n#\n# This Source Code Form is subject to the terms of the Mozilla Public License,\n# v. 2.0. If a copy of the MPL was not distributed with this file, You can\n# obtain one at https://mozilla.org/MPL/2.0/.\n#\n# END HEADER\n\nimport codecs\nimport importlib\nimport inspect\nimport platform\nimport sys\nimport time\nimport typing\n\nPYPY = platform.python_implementation() == \"PyPy\"\nCAN_PACK_HALF_FLOAT = sys.version_info[:2] >= (3, 6)\nWINDOWS = platform.system() == \"Windows\"\n\n\ndef bit_length(n):\n    return n.bit_length()\n\n\ndef str_to_bytes(s):\n    return s.encode(a_good_encoding())\n\n\ndef escape_unicode_characters(s):\n    return codecs.encode(s, \"unicode_escape\").decode(\"ascii\")\n\n\ndef int_from_bytes(data):\n    return int.from_bytes(data, \"big\")\n\n\ndef int_to_bytes(i, size):\n    return i.to_bytes(size, \"big\")\n\n\ndef int_to_byte(i):\n    return bytes([i])\n\n\ndef benchmark_time():\n    return time.monotonic()\n\n\ndef a_good_encoding():\n    return \"utf-8\"\n\n\ndef to_unicode(x):\n    if isinstance(x, str):\n        return x\n    else:\n        return x.decode(a_good_encoding())\n\n\ndef qualname(f):\n    try:\n        return f.__qualname__\n    except AttributeError:\n        return f.__name__\n\n\ntry:\n    # These types are new in Python 3.7, but also (partially) backported to the\n    # typing backport on PyPI.  Use if possible; or fall back to older names.\n    typing_root_type = (typing._Final, typing._GenericAlias)  # type: ignore\n    ForwardRef = typing.ForwardRef  # type: ignore\nexcept AttributeError:\n    typing_root_type = (typing.TypingMeta, typing.TypeVar)  # type: ignore\n    try:\n        typing_root_type += (typing._Union,)  # type: ignore\n    except AttributeError:\n        pass\n    ForwardRef = typing._ForwardRef  # type: ignore\n\n\ndef is_typed_named_tuple(cls):\n    \"\"\"Return True if cls is probably a subtype of `typing.NamedTuple`.\n\n    Unfortunately types created with `class T(NamedTuple):` actually\n    subclass `tuple` directly rather than NamedTuple.  This is annoying,\n    and means we just have to hope that nobody defines a different tuple\n    subclass with similar attributes.\n    \"\"\"\n    return (\n        issubclass(cls, tuple)\n        and hasattr(cls, \"_fields\")\n        and hasattr(cls, \"_field_types\")\n    )\n\n\nif sys.version_info[:2] < (3, 6):\n    # When we drop support for Python 3.5, `get_type_hints` and\n    # `is_typed_named_tuple` should be moved to reflection.py\n\n    def get_type_hints(thing):\n        if inspect.isclass(thing) and not hasattr(thing, \"__signature__\"):\n            if is_typed_named_tuple(thing):\n                # Special handling for typing.NamedTuple\n                return thing._field_types  # type: ignore\n            thing = thing.__init__  # type: ignore\n        try:\n            spec = inspect.getfullargspec(thing)\n            return {\n                k: v\n                for k, v in spec.annotations.items()\n                if k in (spec.args + spec.kwonlyargs) and isinstance(v, type)\n            }\n        except TypeError:\n            return {}\n\n\nelse:\n\n    def get_type_hints(thing):\n        if inspect.isclass(thing) and not hasattr(thing, \"__signature__\"):\n            if is_typed_named_tuple(thing):\n                # Special handling for typing.NamedTuple\n                return thing._field_types  # type: ignore\n            thing = thing.__init__  # type: ignore\n        try:\n            return typing.get_type_hints(thing)\n        except TypeError:\n            return {}\n\n\nimportlib_invalidate_caches = getattr(importlib, \"invalidate_caches\", lambda: ())\n\n\ndef update_code_location(code, newfile, newlineno):\n    \"\"\"Take a code object and lie shamelessly about where it comes from.\n\n    Why do we want to do this? It's for really shallow reasons involving\n    hiding the hypothesis_temporary_module code from test runners like\n    pytest's verbose mode. This is a vastly disproportionate terrible\n    hack that I've done purely for vanity, and if you're reading this\n    code you're probably here because it's broken something and now\n    you're angry at me. Sorry.\n    \"\"\"\n    if hasattr(code, \"replace\"):\n        # Python 3.8 added positional-only params (PEP 570), and thus changed\n        # the layout of code objects.  In beta1, the `.replace()` method was\n        # added to facilitate future-proof code.  See BPO-37032 for details.\n        return code.replace(co_filename=newfile, co_firstlineno=newlineno)\n\n    # This field order is accurate for 3.5 - 3.7, but not 3.8 when a new field\n    # was added for positional-only arguments.  However it also added a .replace()\n    # method that we use instead of field indices, so they're fine as-is.\n    CODE_FIELD_ORDER = [\n        \"co_argcount\",\n        \"co_kwonlyargcount\",\n        \"co_nlocals\",\n        \"co_stacksize\",\n        \"co_flags\",\n        \"co_code\",\n        \"co_consts\",\n        \"co_names\",\n        \"co_varnames\",\n        \"co_filename\",\n        \"co_name\",\n        \"co_firstlineno\",\n        \"co_lnotab\",\n        \"co_freevars\",\n        \"co_cellvars\",\n    ]\n    unpacked = [getattr(code, name) for name in CODE_FIELD_ORDER]\n    unpacked[CODE_FIELD_ORDER.index(\"co_filename\")] = newfile\n    unpacked[CODE_FIELD_ORDER.index(\"co_firstlineno\")] = newlineno\n    return type(code)(*unpacked)\n\n\ndef cast_unicode(s, encoding=None):\n    if isinstance(s, bytes):\n        return s.decode(encoding or a_good_encoding(), \"replace\")\n    return s\n\n\ndef get_stream_enc(stream, default=None):\n    return getattr(stream, \"encoding\", None) or default\n\n\n# Under Python 2, math.floor and math.ceil return floats, which cannot\n# represent large integers - eg `float(2**53) == float(2**53 + 1)`.\n# We therefore implement them entirely in (long) integer operations.\n# We use the same trick on Python 3, because Numpy values and other\n# custom __floor__ or __ceil__ methods may convert via floats.\n# See issue #1667, Numpy issue 9068.\ndef floor(x):\n    y = int(x)\n    if y != x and x < 0:\n        return y - 1\n    return y\n\n\ndef ceil(x):\n    y = int(x)\n    if y != x and x > 0:\n        return y + 1\n    return y\n\n\ntry:\n    from django.test import TransactionTestCase\n\n    def bad_django_TestCase(runner):\n        if runner is None:\n            return False\n        if not isinstance(runner, TransactionTestCase):\n            return False\n\n        from hypothesis.extra.django._impl import HypothesisTestCase\n\n        return not isinstance(runner, HypothesisTestCase)\n\n\nexcept Exception:\n    # Can't use ImportError, because of e.g. Django config errors\n    def bad_django_TestCase(runner):\n        return False\n", "path": "hypothesis-python/src/hypothesis/internal/compat.py"}], "after_files": [{"content": "# This file is part of Hypothesis, which may be found at\n# https://github.com/HypothesisWorks/hypothesis/\n#\n# Most of this work is copyright (C) 2013-2020 David R. MacIver\n# (david@drmaciver.com), but it contains contributions by others. See\n# CONTRIBUTING.rst for a full list of people who may hold copyright, and\n# consult the git log if you need to determine who owns an individual\n# contribution.\n#\n# This Source Code Form is subject to the terms of the Mozilla Public License,\n# v. 2.0. If a copy of the MPL was not distributed with this file, You can\n# obtain one at https://mozilla.org/MPL/2.0/.\n#\n# END HEADER\n\nimport codecs\nimport importlib\nimport inspect\nimport platform\nimport sys\nimport time\nimport typing\n\nPYPY = platform.python_implementation() == \"PyPy\"\nCAN_PACK_HALF_FLOAT = sys.version_info[:2] >= (3, 6)\nWINDOWS = platform.system() == \"Windows\"\n\n\ndef bit_length(n):\n    return n.bit_length()\n\n\ndef str_to_bytes(s):\n    return s.encode(a_good_encoding())\n\n\ndef escape_unicode_characters(s):\n    return codecs.encode(s, \"unicode_escape\").decode(\"ascii\")\n\n\ndef int_from_bytes(data):\n    return int.from_bytes(data, \"big\")\n\n\ndef int_to_bytes(i, size):\n    return i.to_bytes(size, \"big\")\n\n\ndef int_to_byte(i):\n    return bytes([i])\n\n\ndef benchmark_time():\n    return time.monotonic()\n\n\ndef a_good_encoding():\n    return \"utf-8\"\n\n\ndef to_unicode(x):\n    if isinstance(x, str):\n        return x\n    else:\n        return x.decode(a_good_encoding())\n\n\ndef qualname(f):\n    try:\n        return f.__qualname__\n    except AttributeError:\n        return f.__name__\n\n\ntry:\n    # These types are new in Python 3.7, but also (partially) backported to the\n    # typing backport on PyPI.  Use if possible; or fall back to older names.\n    typing_root_type = (typing._Final, typing._GenericAlias)  # type: ignore\n    ForwardRef = typing.ForwardRef  # type: ignore\nexcept AttributeError:\n    typing_root_type = (typing.TypingMeta, typing.TypeVar)  # type: ignore\n    try:\n        typing_root_type += (typing._Union,)  # type: ignore\n    except AttributeError:\n        pass\n    ForwardRef = typing._ForwardRef  # type: ignore\n\n\ndef is_typed_named_tuple(cls):\n    \"\"\"Return True if cls is probably a subtype of `typing.NamedTuple`.\n\n    Unfortunately types created with `class T(NamedTuple):` actually\n    subclass `tuple` directly rather than NamedTuple.  This is annoying,\n    and means we just have to hope that nobody defines a different tuple\n    subclass with similar attributes.\n    \"\"\"\n    return (\n        issubclass(cls, tuple)\n        and hasattr(cls, \"_fields\")\n        and hasattr(cls, \"_field_types\")\n    )\n\n\nif sys.version_info[:2] < (3, 6):\n    # When we drop support for Python 3.5, `get_type_hints` and\n    # `is_typed_named_tuple` should be moved to reflection.py\n\n    def get_type_hints(thing):\n        if inspect.isclass(thing) and not hasattr(thing, \"__signature__\"):\n            if is_typed_named_tuple(thing):\n                # Special handling for typing.NamedTuple\n                return thing._field_types  # type: ignore\n            thing = thing.__init__  # type: ignore\n        try:\n            spec = inspect.getfullargspec(thing)\n            return {\n                k: v\n                for k, v in spec.annotations.items()\n                if k in (spec.args + spec.kwonlyargs) and isinstance(v, type)\n            }\n        except TypeError:\n            return {}\n\n\nelse:\n\n    def get_type_hints(thing):\n        \"\"\"Like the typing version, but tries harder and never errors.\n\n        Tries harder: if the thing to inspect is a class but typing.get_type_hints\n        raises an error or returns no hints, then this function will try calling it\n        on the __init__ method.  This second step often helps with user-defined\n        classes on older versions of Python.\n\n        Never errors: instead of raising TypeError for uninspectable objects, or\n        NameError for unresolvable forward references, just return an empty dict.\n        \"\"\"\n        try:\n            hints = typing.get_type_hints(thing)\n        except (TypeError, NameError):\n            hints = {}\n        if hints or not inspect.isclass(thing):\n            return hints\n        try:\n            return typing.get_type_hints(thing.__init__)\n        except (TypeError, NameError, AttributeError):\n            return {}\n\n\nimportlib_invalidate_caches = getattr(importlib, \"invalidate_caches\", lambda: ())\n\n\ndef update_code_location(code, newfile, newlineno):\n    \"\"\"Take a code object and lie shamelessly about where it comes from.\n\n    Why do we want to do this? It's for really shallow reasons involving\n    hiding the hypothesis_temporary_module code from test runners like\n    pytest's verbose mode. This is a vastly disproportionate terrible\n    hack that I've done purely for vanity, and if you're reading this\n    code you're probably here because it's broken something and now\n    you're angry at me. Sorry.\n    \"\"\"\n    if hasattr(code, \"replace\"):\n        # Python 3.8 added positional-only params (PEP 570), and thus changed\n        # the layout of code objects.  In beta1, the `.replace()` method was\n        # added to facilitate future-proof code.  See BPO-37032 for details.\n        return code.replace(co_filename=newfile, co_firstlineno=newlineno)\n\n    # This field order is accurate for 3.5 - 3.7, but not 3.8 when a new field\n    # was added for positional-only arguments.  However it also added a .replace()\n    # method that we use instead of field indices, so they're fine as-is.\n    CODE_FIELD_ORDER = [\n        \"co_argcount\",\n        \"co_kwonlyargcount\",\n        \"co_nlocals\",\n        \"co_stacksize\",\n        \"co_flags\",\n        \"co_code\",\n        \"co_consts\",\n        \"co_names\",\n        \"co_varnames\",\n        \"co_filename\",\n        \"co_name\",\n        \"co_firstlineno\",\n        \"co_lnotab\",\n        \"co_freevars\",\n        \"co_cellvars\",\n    ]\n    unpacked = [getattr(code, name) for name in CODE_FIELD_ORDER]\n    unpacked[CODE_FIELD_ORDER.index(\"co_filename\")] = newfile\n    unpacked[CODE_FIELD_ORDER.index(\"co_firstlineno\")] = newlineno\n    return type(code)(*unpacked)\n\n\ndef cast_unicode(s, encoding=None):\n    if isinstance(s, bytes):\n        return s.decode(encoding or a_good_encoding(), \"replace\")\n    return s\n\n\ndef get_stream_enc(stream, default=None):\n    return getattr(stream, \"encoding\", None) or default\n\n\n# Under Python 2, math.floor and math.ceil return floats, which cannot\n# represent large integers - eg `float(2**53) == float(2**53 + 1)`.\n# We therefore implement them entirely in (long) integer operations.\n# We use the same trick on Python 3, because Numpy values and other\n# custom __floor__ or __ceil__ methods may convert via floats.\n# See issue #1667, Numpy issue 9068.\ndef floor(x):\n    y = int(x)\n    if y != x and x < 0:\n        return y - 1\n    return y\n\n\ndef ceil(x):\n    y = int(x)\n    if y != x and x > 0:\n        return y + 1\n    return y\n\n\ntry:\n    from django.test import TransactionTestCase\n\n    def bad_django_TestCase(runner):\n        if runner is None:\n            return False\n        if not isinstance(runner, TransactionTestCase):\n            return False\n\n        from hypothesis.extra.django._impl import HypothesisTestCase\n\n        return not isinstance(runner, HypothesisTestCase)\n\n\nexcept Exception:\n    # Can't use ImportError, because of e.g. Django config errors\n    def bad_django_TestCase(runner):\n        return False\n", "path": "hypothesis-python/src/hypothesis/internal/compat.py"}]}