1# This file is part of Hypothesis, which may be found at
2# https://github.com/HypothesisWorks/hypothesis/
3#
4# Copyright the Hypothesis Authors.
5# Individual contributors are listed in AUTHORS.rst and the git log.
6#
7# This Source Code Form is subject to the terms of the Mozilla Public License,
8# v. 2.0. If a copy of the MPL was not distributed with this file, You can
9# obtain one at https://mozilla.org/MPL/2.0/.
10
11from collections.abc import Hashable
12from typing import Any, Optional
13
14from hypothesis.internal.conjecture.data import ConjectureData
15from hypothesis.strategies._internal import SearchStrategy
16from hypothesis.strategies._internal.strategies import Ex
17
18
19class SharedStrategy(SearchStrategy[Ex]):
20 def __init__(self, base: SearchStrategy[Ex], key: Optional[Hashable] = None):
21 self.key = key
22 self.base = base
23
24 @property
25 def supports_find(self) -> bool:
26 return self.base.supports_find
27
28 def __repr__(self) -> str:
29 if self.key is not None:
30 return f"shared({self.base!r}, key={self.key!r})"
31 else:
32 return f"shared({self.base!r})"
33
34 # Ideally would be -> Ex, but key collisions with different-typed values are
35 # possible. See https://github.com/HypothesisWorks/hypothesis/issues/4301.
36 def do_draw(self, data: ConjectureData) -> Any:
37 key = self.key or self
38 if key not in data._shared_strategy_draws:
39 data._shared_strategy_draws[key] = data.draw(self.base)
40 return data._shared_strategy_draws[key]