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 hypothesis.strategies._internal import SearchStrategy
12
13SHARED_STRATEGY_ATTRIBUTE = "_hypothesis_shared_strategies"
14
15
16class SharedStrategy(SearchStrategy):
17 def __init__(self, base, key=None):
18 self.key = key
19 self.base = base
20
21 @property
22 def supports_find(self):
23 return self.base.supports_find
24
25 def __repr__(self):
26 if self.key is not None:
27 return f"shared({self.base!r}, key={self.key!r})"
28 else:
29 return f"shared({self.base!r})"
30
31 def do_draw(self, data):
32 if not hasattr(data, SHARED_STRATEGY_ATTRIBUTE):
33 setattr(data, SHARED_STRATEGY_ATTRIBUTE, {})
34 sharing = getattr(data, SHARED_STRATEGY_ATTRIBUTE)
35 key = self.key or self
36 if key not in sharing:
37 sharing[key] = data.draw(self.base)
38 return sharing[key]