Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/hypothesis/strategies/_internal/core.py: 34%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

857 statements  

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 

11import codecs 

12import enum 

13import math 

14import operator 

15import random 

16import re 

17import string 

18import sys 

19import typing 

20import warnings 

21from collections.abc import Callable, Collection, Hashable, Iterable, Sequence 

22from contextvars import ContextVar 

23from decimal import Context, Decimal, localcontext 

24from fractions import Fraction 

25from functools import reduce 

26from inspect import Parameter, Signature, isabstract, isclass 

27from re import Pattern 

28from types import EllipsisType, FunctionType, GenericAlias 

29from typing import ( 

30 Annotated, 

31 Any, 

32 AnyStr, 

33 Concatenate, 

34 Literal, 

35 NewType, 

36 NoReturn, 

37 ParamSpec, 

38 Protocol, 

39 TypeAlias, 

40 TypeVar, 

41 cast, 

42 get_args, 

43 get_origin, 

44 overload, 

45) 

46from uuid import UUID 

47 

48from hypothesis.control import ( 

49 cleanup, 

50 current_build_context, 

51 deprecate_random_in_strategy, 

52 note, 

53 should_note, 

54) 

55from hypothesis.errors import ( 

56 HypothesisSideeffectWarning, 

57 HypothesisWarning, 

58 InvalidArgument, 

59 ResolutionFailed, 

60 RewindRecursive, 

61 SmallSearchSpaceWarning, 

62) 

63from hypothesis.internal.cathetus import cathetus 

64from hypothesis.internal.charmap import ( 

65 Categories, 

66 CategoryName, 

67 as_general_categories, 

68 categories as all_categories, 

69) 

70from hypothesis.internal.compat import ( 

71 bit_count, 

72 ceil, 

73 floor, 

74 get_type_hints, 

75 is_typed_named_tuple, 

76) 

77from hypothesis.internal.conjecture.data import ConjectureData 

78from hypothesis.internal.conjecture.utils import ( 

79 calc_label_from_callable, 

80 calc_label_from_name, 

81 check_sample, 

82 combine_labels, 

83 identity, 

84) 

85from hypothesis.internal.entropy import get_seeder_and_restorer 

86from hypothesis.internal.floats import float_of 

87from hypothesis.internal.reflection import ( 

88 define_function_signature, 

89 get_pretty_function_description, 

90 get_signature, 

91 is_first_param_referenced_in_function, 

92 nicerepr, 

93 repr_call, 

94 required_args, 

95) 

96from hypothesis.internal.validation import ( 

97 check_type, 

98 check_valid_integer, 

99 check_valid_interval, 

100 check_valid_magnitude, 

101 check_valid_size, 

102 check_valid_sizes, 

103 try_convert, 

104) 

105from hypothesis.strategies._internal import SearchStrategy, check_strategy 

106from hypothesis.strategies._internal.collections import ( 

107 FixedDictStrategy, 

108 ListStrategy, 

109 TupleStrategy, 

110 UniqueListStrategy, 

111 UniqueSampledListStrategy, 

112 tuples, 

113) 

114from hypothesis.strategies._internal.deferred import DeferredStrategy 

115from hypothesis.strategies._internal.functions import FunctionStrategy 

116from hypothesis.strategies._internal.lazy import LazyStrategy, unwrap_strategies 

117from hypothesis.strategies._internal.misc import BooleansStrategy, just, none, nothing 

118from hypothesis.strategies._internal.numbers import ( 

119 IntegersStrategy, 

120 Real, 

121 floats, 

122 integers, 

123) 

124from hypothesis.strategies._internal.recursive import RecursiveStrategy 

125from hypothesis.strategies._internal.shared import SharedStrategy 

126from hypothesis.strategies._internal.strategies import ( 

127 Ex, 

128 SampledFromStrategy, 

129 T, 

130 one_of, 

131) 

132from hypothesis.strategies._internal.strings import ( 

133 BytesStrategy, 

134 OneCharStringStrategy, 

135 TextStrategy, 

136 _check_is_single_character, 

137) 

138from hypothesis.strategies._internal.utils import cacheable, defines_strategy 

139from hypothesis.utils.conventions import not_set 

140from hypothesis.utils.deprecation import note_deprecation 

141from hypothesis.vendor.pretty import ArgLabelsT, RepresentationPrinter 

142 

143 

144@cacheable 

145@defines_strategy(force_reusable_values=True) 

146def booleans() -> SearchStrategy[bool]: 

147 """Returns a strategy which generates instances of :class:`python:bool`. 

148 

149 Examples from this strategy will shrink towards ``False`` (i.e. 

150 shrinking will replace ``True`` with ``False`` where possible). 

151 """ 

152 return BooleansStrategy() 

153 

154 

155@overload 

156def sampled_from(elements: Sequence[T]) -> SearchStrategy[T]: # pragma: no cover 

157 ... 

158 

159 

160@overload 

161def sampled_from(elements: type[enum.Enum]) -> SearchStrategy[Any]: # pragma: no cover 

162 # `SearchStrategy[Enum]` is unreliable due to metaclass issues. 

163 ... 

164 

165 

166@overload 

167def sampled_from( 

168 elements: type[enum.Enum] | Sequence[Any], 

169) -> SearchStrategy[Any]: # pragma: no cover 

170 ... 

171 

172 

173@defines_strategy(eager="try") 

174def sampled_from( 

175 elements: type[enum.Enum] | Sequence[Any], 

176) -> SearchStrategy[Any]: 

177 """Returns a strategy which generates any value present in ``elements``. 

178 

179 Note that as with :func:`~hypothesis.strategies.just`, values will not be 

180 copied and thus you should be careful of using mutable data. 

181 

182 ``sampled_from`` supports ordered collections, as well as 

183 :class:`~python:enum.Enum` objects. :class:`~python:enum.Flag` objects 

184 may also generate any combination of their members. 

185 

186 Examples from this strategy shrink by replacing them with values earlier in 

187 the list. So e.g. ``sampled_from([10, 1])`` will shrink by trying to replace 

188 1 values with 10, and ``sampled_from([1, 10])`` will shrink by trying to 

189 replace 10 values with 1. 

190 

191 It is an error to sample from an empty sequence, because returning :func:`nothing` 

192 makes it too easy to silently drop parts of compound strategies. If you need 

193 that behaviour, use ``sampled_from(seq) if seq else nothing()``. 

194 """ 

195 values = check_sample(elements, "sampled_from") 

196 force_repr = None 

197 # check_sample converts to tuple unconditionally, but we want to preserve 

198 # square braces for list reprs. 

199 # This will not cover custom sequence implementations which return different 

200 # braces (or other, more unusual things) for their reprs, but this is a tradeoff 

201 # between repr accuracy and greedily-evaluating all sequence reprs (at great 

202 # cost for large sequences). 

203 force_repr_braces = ("[", "]") if isinstance(elements, list) else None 

204 if isinstance(elements, type) and issubclass(elements, enum.Enum): 

205 force_repr = f"sampled_from({elements.__module__}.{elements.__name__})" 

206 

207 if isclass(elements) and issubclass(elements, enum.Flag): 

208 # Combinations of enum.Flag members (including empty) are also members. We generate these 

209 # dynamically, because static allocation takes O(2^n) memory. LazyStrategy is used for the 

210 # ease of force_repr. 

211 # Add all named values, both flag bits (== list(elements)) and aliases. The aliases are 

212 # necessary for full coverage for flags that would fail enum.NAMED_FLAGS check, and they 

213 # are also nice values to shrink to. 

214 flags = sorted( 

215 set(elements.__members__.values()), 

216 key=lambda v: (bit_count(v.value), v.value), 

217 ) 

218 # Finally, try to construct the empty state if it is not named. It's placed at the 

219 # end so that we shrink to named values. 

220 flags_with_empty = flags 

221 if not flags or flags[0].value != 0: 

222 try: 

223 flags_with_empty = [*flags, elements(0)] 

224 except TypeError: # pragma: no cover 

225 # Happens on some python versions (at least 3.12) when there are no named values 

226 pass 

227 inner = [ 

228 # Consider one or no named flags set, with shrink-to-named-flag behaviour. 

229 # Special cases (length zero or one) are handled by the inner sampled_from. 

230 sampled_from(flags_with_empty), 

231 ] 

232 if len(flags) > 1: 

233 inner += [ 

234 # Uniform distribution over number of named flags or combinations set. The overlap 

235 # at r=1 is intentional, it may lead to oversampling but gives consistent shrinking 

236 # behaviour. 

237 integers(min_value=1, max_value=len(flags)) 

238 .flatmap(lambda r: sets(sampled_from(flags), min_size=r, max_size=r)) 

239 .map(lambda s: elements(reduce(operator.or_, s))), 

240 ] 

241 return LazyStrategy(one_of, args=inner, kwargs={}, force_repr=force_repr) 

242 if not values: 

243 

244 def has_annotations(elements): 

245 if sys.version_info[:2] < (3, 14): 

246 return vars(elements).get("__annotations__") 

247 else: # pragma: no cover # covered by 3.14 tests 

248 import annotationlib 

249 

250 return bool(annotationlib.get_annotations(elements)) 

251 

252 if ( 

253 isinstance(elements, type) 

254 and issubclass(elements, enum.Enum) 

255 and has_annotations(elements) 

256 ): 

257 # See https://github.com/HypothesisWorks/hypothesis/issues/2923 

258 raise InvalidArgument( 

259 f"Cannot sample from {elements.__module__}.{elements.__name__} " 

260 "because it contains no elements. It does however have annotations, " 

261 "so maybe you tried to write an enum as if it was a dataclass?" 

262 ) 

263 raise InvalidArgument("Cannot sample from a length-zero sequence.") 

264 if len(values) == 1: 

265 return just(values[0]) 

266 return SampledFromStrategy( 

267 values, force_repr=force_repr, force_repr_braces=force_repr_braces 

268 ) 

269 

270 

271def _gets_first_item(fn: Callable) -> bool: 

272 # Introspection for either `itemgetter(0)`, or `lambda x: x[0]` 

273 if isinstance(fn, FunctionType): 

274 s = get_pretty_function_description(fn) 

275 return bool(re.fullmatch(s, r"lambda ([a-z]+): \1\[0\]")) 

276 return isinstance(fn, operator.itemgetter) and repr(fn) == "operator.itemgetter(0)" 

277 

278 

279@cacheable 

280@defines_strategy() 

281def lists( 

282 elements: SearchStrategy[Ex], 

283 *, 

284 min_size: int = 0, 

285 max_size: int | None = None, 

286 unique_by: ( 

287 None | Callable[[Ex], Hashable] | tuple[Callable[[Ex], Hashable], ...] 

288 ) = None, 

289 unique: bool = False, 

290) -> SearchStrategy[list[Ex]]: 

291 """Returns a list containing values drawn from elements with length in the 

292 interval [min_size, max_size] (no bounds in that direction if these are 

293 None). If max_size is 0, only the empty list will be drawn. 

294 

295 If ``unique`` is True (or something that evaluates to True), we compare direct 

296 object equality, as if unique_by was ``lambda x: x``. This comparison only 

297 works for hashable types. 

298 

299 If ``unique_by`` is not None it must be a callable or tuple of callables 

300 returning a hashable type when given a value drawn from elements. The 

301 resulting list will satisfy the condition that for ``i`` != ``j``, 

302 ``unique_by(result[i])`` != ``unique_by(result[j])``. 

303 

304 If ``unique_by`` is a tuple of callables the uniqueness will be respective 

305 to each callable. 

306 

307 For example, the following will produce two columns of integers with both 

308 columns being unique respectively. 

309 

310 .. code-block:: pycon 

311 

312 >>> twoints = st.tuples(st.integers(), st.integers()) 

313 >>> st.lists(twoints, unique_by=(lambda x: x[0], lambda x: x[1])) 

314 

315 Examples from this strategy shrink by trying to remove elements from the 

316 list, and by shrinking each individual element of the list. 

317 """ 

318 check_valid_sizes(min_size, max_size) 

319 check_strategy(elements, "elements") 

320 if unique: 

321 if unique_by is not None: 

322 raise InvalidArgument( 

323 "cannot specify both unique and unique_by " 

324 "(you probably only want to set unique_by)" 

325 ) 

326 else: 

327 unique_by = identity 

328 

329 if max_size == 0: 

330 return builds(list) 

331 if unique_by is not None: 

332 if not (callable(unique_by) or isinstance(unique_by, tuple)): 

333 raise InvalidArgument( 

334 f"{unique_by=} is not a callable or tuple of callables" 

335 ) 

336 if callable(unique_by): 

337 unique_by = (unique_by,) 

338 if len(unique_by) == 0: 

339 raise InvalidArgument("unique_by is empty") 

340 for i, f in enumerate(unique_by): 

341 if not callable(f): 

342 raise InvalidArgument(f"unique_by[{i}]={f!r} is not a callable") 

343 # Note that lazy strategies automatically unwrap when passed to a defines_strategy 

344 # function. 

345 tuple_suffixes = None 

346 if ( 

347 # We're generating a list of tuples unique by the first element, perhaps 

348 # via st.dictionaries(), and this will be more efficient if we rearrange 

349 # our strategy somewhat to draw the first element then draw add the rest. 

350 isinstance(elements, TupleStrategy) 

351 and len(elements.element_strategies) >= 1 

352 and all(_gets_first_item(fn) for fn in unique_by) 

353 ): 

354 unique_by = (identity,) 

355 tuple_suffixes = TupleStrategy(elements.element_strategies[1:]) 

356 elements = elements.element_strategies[0] 

357 

358 # UniqueSampledListStrategy offers a substantial performance improvement for 

359 # unique arrays with few possible elements, e.g. of eight-bit integer types. 

360 if ( 

361 isinstance(elements, IntegersStrategy) 

362 and elements.start is not None 

363 and elements.end is not None 

364 and (elements.end - elements.start) <= 255 

365 ): 

366 elements = SampledFromStrategy( 

367 sorted(range(elements.start, elements.end + 1), key=abs) # type: ignore 

368 if elements.end < 0 or elements.start > 0 

369 else ( 

370 list(range(elements.end + 1)) 

371 + list(range(-1, elements.start - 1, -1)) 

372 ) 

373 ) 

374 

375 if isinstance(elements, SampledFromStrategy): 

376 element_count = len(elements.elements) 

377 if min_size > element_count: 

378 raise InvalidArgument( 

379 f"Cannot create a collection of {min_size=} unique " 

380 f"elements with values drawn from only {element_count} distinct " 

381 "elements" 

382 ) 

383 

384 if max_size is not None: 

385 max_size = min(max_size, element_count) 

386 else: 

387 max_size = element_count 

388 

389 return UniqueSampledListStrategy( 

390 elements=elements, 

391 max_size=max_size, 

392 min_size=min_size, 

393 keys=unique_by, 

394 tuple_suffixes=tuple_suffixes, 

395 ) 

396 

397 return UniqueListStrategy( 

398 elements=elements, 

399 max_size=max_size, 

400 min_size=min_size, 

401 keys=unique_by, 

402 tuple_suffixes=tuple_suffixes, 

403 ) 

404 return ListStrategy(elements, min_size=min_size, max_size=max_size) 

405 

406 

407@cacheable 

408@defines_strategy() 

409def sets( 

410 elements: SearchStrategy[Ex], 

411 *, 

412 min_size: int = 0, 

413 max_size: int | None = None, 

414) -> SearchStrategy[set[Ex]]: 

415 """This has the same behaviour as lists, but returns sets instead. 

416 

417 Note that Hypothesis cannot tell if values are drawn from elements 

418 are hashable until running the test, so you can define a strategy 

419 for sets of an unhashable type but it will fail at test time. 

420 

421 Examples from this strategy shrink by trying to remove elements from the 

422 set, and by shrinking each individual element of the set. 

423 """ 

424 return lists( 

425 elements=elements, min_size=min_size, max_size=max_size, unique=True 

426 ).map(set) 

427 

428 

429@cacheable 

430@defines_strategy() 

431def frozensets( 

432 elements: SearchStrategy[Ex], 

433 *, 

434 min_size: int = 0, 

435 max_size: int | None = None, 

436) -> SearchStrategy[frozenset[Ex]]: 

437 """This is identical to the sets function but instead returns 

438 frozensets.""" 

439 return lists( 

440 elements=elements, min_size=min_size, max_size=max_size, unique=True 

441 ).map(frozenset) 

442 

443 

444class PrettyIter: 

445 def __init__(self, values): 

446 self._values = values 

447 self._iter = iter(self._values) 

448 

449 def __iter__(self): 

450 return self._iter 

451 

452 def __next__(self): 

453 return next(self._iter) 

454 

455 def __repr__(self) -> str: 

456 return f"iter({self._values!r})" 

457 

458 

459@defines_strategy() 

460def iterables( 

461 elements: SearchStrategy[Ex], 

462 *, 

463 min_size: int = 0, 

464 max_size: int | None = None, 

465 unique_by: ( 

466 None | Callable[[Ex], Hashable] | tuple[Callable[[Ex], Hashable], ...] 

467 ) = None, 

468 unique: bool = False, 

469) -> SearchStrategy[Iterable[Ex]]: 

470 """This has the same behaviour as lists, but returns iterables instead. 

471 

472 Some iterables cannot be indexed (e.g. sets) and some do not have a 

473 fixed length (e.g. generators). This strategy produces iterators, 

474 which cannot be indexed and do not have a fixed length. This ensures 

475 that you do not accidentally depend on sequence behaviour. 

476 """ 

477 return lists( 

478 elements=elements, 

479 min_size=min_size, 

480 max_size=max_size, 

481 unique_by=unique_by, 

482 unique=unique, 

483 ).map(PrettyIter) 

484 

485 

486# this type definition is imprecise, in multiple ways: 

487# * mapping and optional can be of different types: 

488# s: dict[str | int, int] = st.fixed_dictionaries( 

489# {"a": st.integers()}, optional={1: st.integers()} 

490# ) 

491# * the values in either mapping or optional need not all be of the same type: 

492# s: dict[str, int | bool] = st.fixed_dictionaries( 

493# {"a": st.integers(), "b": st.booleans()} 

494# ) 

495# * the arguments may be of any dict-compatible type, in which case the return 

496# value will be of that type instead of dit 

497# 

498# Overloads may help here, but I doubt we'll be able to satisfy all these 

499# constraints. 

500# 

501# Here's some platonic ideal test cases for revealed_types.py, with the understanding 

502# that some may not be achievable: 

503# 

504# ("fixed_dictionaries({'a': booleans()})", "dict[str, bool]"), 

505# ("fixed_dictionaries({'a': booleans(), 'b': integers()})", "dict[str, bool | int]"), 

506# ("fixed_dictionaries({}, optional={'a': booleans()})", "dict[str, bool]"), 

507# ( 

508# "fixed_dictionaries({'a': booleans()}, optional={1: booleans()})", 

509# "dict[str | int, bool]", 

510# ), 

511# ( 

512# "fixed_dictionaries({'a': booleans()}, optional={1: integers()})", 

513# "dict[str | int, bool | int]", 

514# ), 

515 

516 

517@defines_strategy() 

518def fixed_dictionaries( 

519 mapping: dict[T, SearchStrategy[Ex]], 

520 *, 

521 optional: dict[T, SearchStrategy[Ex]] | None = None, 

522) -> SearchStrategy[dict[T, Ex]]: 

523 """Generates a dictionary of the same type as mapping with a fixed set of 

524 keys mapping to strategies. ``mapping`` must be a dict subclass. 

525 

526 Generated values have all keys present in mapping, in iteration order, 

527 with the corresponding values drawn from mapping[key]. 

528 

529 If ``optional`` is passed, the generated value *may or may not* contain each 

530 key from ``optional`` and a value drawn from the corresponding strategy. 

531 Generated values may contain optional keys in an arbitrary order. 

532 

533 Examples from this strategy shrink by shrinking each individual value in 

534 the generated dictionary, and omitting optional key-value pairs. 

535 """ 

536 check_type(dict, mapping, "mapping") 

537 for k, v in mapping.items(): 

538 check_strategy(v, f"mapping[{k!r}]") 

539 

540 if optional is not None: 

541 check_type(dict, optional, "optional") 

542 for k, v in optional.items(): 

543 check_strategy(v, f"optional[{k!r}]") 

544 if type(mapping) != type(optional): 

545 raise InvalidArgument( 

546 f"Got arguments of different types: " 

547 f"mapping={nicerepr(type(mapping))}, " 

548 f"optional={nicerepr(type(optional))}" 

549 ) 

550 if set(mapping) & set(optional): 

551 raise InvalidArgument( 

552 "The following keys were in both mapping and optional, " 

553 f"which is invalid: {set(mapping) & set(optional)!r}" 

554 ) 

555 

556 return FixedDictStrategy(mapping, optional=optional) 

557 

558 

559_get_first_item = operator.itemgetter(0) 

560 

561 

562@cacheable 

563@defines_strategy() 

564def dictionaries( 

565 keys: SearchStrategy[Ex], 

566 values: SearchStrategy[T], 

567 *, 

568 dict_class: type = dict, 

569 min_size: int = 0, 

570 max_size: int | None = None, 

571) -> SearchStrategy[dict[Ex, T]]: 

572 # Describing the exact dict_class to Mypy drops the key and value types, 

573 # so we report Dict[K, V] instead of Mapping[Any, Any] for now. Sorry! 

574 """Generates dictionaries of type ``dict_class`` with keys drawn from the ``keys`` 

575 argument and values drawn from the ``values`` argument. 

576 

577 The size parameters have the same interpretation as for 

578 :func:`~hypothesis.strategies.lists`. 

579 

580 Examples from this strategy shrink by trying to remove keys from the 

581 generated dictionary, and by shrinking each generated key and value. 

582 """ 

583 check_valid_sizes(min_size, max_size) 

584 if max_size == 0: 

585 return fixed_dictionaries(dict_class()) 

586 check_strategy(keys, "keys") 

587 check_strategy(values, "values") 

588 

589 return lists( 

590 tuples(keys, values), 

591 min_size=min_size, 

592 max_size=max_size, 

593 unique_by=_get_first_item, 

594 ).map(dict_class) 

595 

596 

597@cacheable 

598@defines_strategy(force_reusable_values=True) 

599def characters( 

600 *, 

601 codec: str | None = None, 

602 min_codepoint: int | None = None, 

603 max_codepoint: int | None = None, 

604 categories: Collection[CategoryName] | None = None, 

605 exclude_categories: Collection[CategoryName] | None = None, 

606 exclude_characters: Collection[str] | None = None, 

607 include_characters: Collection[str] | None = None, 

608 # Note: these arguments are deprecated aliases for backwards compatibility 

609 blacklist_categories: Collection[CategoryName] | None = None, 

610 whitelist_categories: Collection[CategoryName] | None = None, 

611 blacklist_characters: Collection[str] | None = None, 

612 whitelist_characters: Collection[str] | None = None, 

613) -> SearchStrategy[str]: 

614 r"""Generates characters, length-one :class:`python:str`\ ings, 

615 following specified filtering rules. 

616 

617 - When no filtering rules are specified, any character can be produced. 

618 - If ``min_codepoint`` or ``max_codepoint`` is specified, then only 

619 characters having a codepoint in that range will be produced. 

620 - If ``categories`` is specified, then only characters from those 

621 Unicode categories will be produced. This is a further restriction, 

622 characters must also satisfy ``min_codepoint`` and ``max_codepoint``. 

623 - If ``exclude_categories`` is specified, then any character from those 

624 categories will not be produced. You must not pass both ``categories`` 

625 and ``exclude_categories``; these arguments are alternative ways to 

626 specify exactly the same thing. 

627 - If ``include_characters`` is specified, then any additional characters 

628 in that list will also be produced. 

629 - If ``exclude_characters`` is specified, then any characters in 

630 that list will be not be produced. Any overlap between 

631 ``include_characters`` and ``exclude_characters`` will raise an 

632 exception. 

633 - If ``codec`` is specified, only characters in the specified `codec encodings`_ 

634 will be produced. 

635 

636 The ``_codepoint`` arguments must be integers between zero and 

637 :obj:`python:sys.maxunicode`. The ``_characters`` arguments must be 

638 collections of length-one unicode strings, such as a unicode string. 

639 

640 The ``_categories`` arguments must be used to specify either the 

641 one-letter Unicode major category or the two-letter Unicode 

642 `general category`_. For example, ``('Nd', 'Lu')`` signifies "Number, 

643 decimal digit" and "Letter, uppercase". A single letter ('major category') 

644 can be given to match all corresponding categories, for example ``'P'`` 

645 for characters in any punctuation category. 

646 

647 We allow codecs from the :mod:`codecs` module and their aliases, platform 

648 specific and user-registered codecs if they are available, and 

649 `python-specific text encodings`_ (but not text or binary transforms). 

650 ``include_characters`` which cannot be encoded using this codec will 

651 raise an exception. If non-encodable codepoints or categories are 

652 explicitly allowed, the ``codec`` argument will exclude them without 

653 raising an exception. 

654 

655 .. _general category: https://en.wikipedia.org/wiki/Unicode_character_property 

656 .. _codec encodings: https://docs.python.org/3/library/codecs.html#encodings-and-unicode 

657 .. _python-specific text encodings: https://docs.python.org/3/library/codecs.html#python-specific-encodings 

658 

659 Examples from this strategy shrink towards the codepoint for ``'0'``, 

660 or the first allowable codepoint after it if ``'0'`` is excluded. 

661 """ 

662 check_valid_size(min_codepoint, "min_codepoint") 

663 check_valid_size(max_codepoint, "max_codepoint") 

664 check_valid_interval(min_codepoint, max_codepoint, "min_codepoint", "max_codepoint") 

665 categories = cast(Categories | None, categories) 

666 if categories is not None and exclude_categories is not None: 

667 raise InvalidArgument( 

668 f"Pass at most one of {categories=} and {exclude_categories=} - " 

669 "these arguments both specify which categories are allowed, so it " 

670 "doesn't make sense to use both in a single call." 

671 ) 

672 

673 # Handle deprecation of whitelist/blacklist arguments 

674 has_old_arg = any(v is not None for k, v in locals().items() if "list" in k) 

675 has_new_arg = any(v is not None for k, v in locals().items() if "lude" in k) 

676 if has_old_arg and has_new_arg: 

677 raise InvalidArgument( 

678 "The deprecated blacklist/whitelist arguments cannot be used in " 

679 "the same call as their replacement include/exclude arguments." 

680 ) 

681 if blacklist_categories is not None: 

682 exclude_categories = blacklist_categories 

683 if whitelist_categories is not None: 

684 categories = whitelist_categories 

685 if blacklist_characters is not None: 

686 exclude_characters = blacklist_characters 

687 if whitelist_characters is not None: 

688 include_characters = whitelist_characters 

689 

690 if ( 

691 min_codepoint is None 

692 and max_codepoint is None 

693 and categories is None 

694 and exclude_categories is None 

695 and include_characters is not None 

696 and codec is None 

697 ): 

698 raise InvalidArgument( 

699 "Nothing is excluded by other arguments, so passing only " 

700 f"{include_characters=} would have no effect. " 

701 "Also pass categories=(), or use " 

702 f"sampled_from({include_characters!r}) instead." 

703 ) 

704 exclude_characters = exclude_characters or "" 

705 include_characters = include_characters or "" 

706 if not_one_char := [c for c in exclude_characters if len(c) != 1]: 

707 raise InvalidArgument( 

708 "Elements of exclude_characters are required to be a single character, " 

709 f"but {not_one_char!r} passed in {exclude_characters=} was not." 

710 ) 

711 if not_one_char := [c for c in include_characters if len(c) != 1]: 

712 raise InvalidArgument( 

713 "Elements of include_characters are required to be a single character, " 

714 f"but {not_one_char!r} passed in {include_characters=} was not." 

715 ) 

716 overlap = set(exclude_characters).intersection(include_characters) 

717 if overlap: 

718 raise InvalidArgument( 

719 f"Characters {sorted(overlap)!r} are present in both " 

720 f"{include_characters=} and {exclude_characters=}" 

721 ) 

722 if categories is not None: 

723 categories = as_general_categories(categories, "categories") 

724 if exclude_categories is not None: 

725 exclude_categories = as_general_categories( 

726 exclude_categories, "exclude_categories" 

727 ) 

728 if categories is not None and not categories and not include_characters: 

729 raise InvalidArgument( 

730 "When `categories` is an empty collection and there are " 

731 "no characters specified in include_characters, nothing can " 

732 "be generated by the characters() strategy." 

733 ) 

734 both_cats = set(exclude_categories or ()).intersection(categories or ()) 

735 if both_cats: 

736 # Note: we check that exactly one of `categories` or `exclude_categories` is 

737 # passed above, but retain this older check for the deprecated arguments. 

738 raise InvalidArgument( 

739 f"Categories {sorted(both_cats)!r} are present in both " 

740 f"{categories=} and {exclude_categories=}" 

741 ) 

742 elif exclude_categories is not None: 

743 categories = set(all_categories()) - set(exclude_categories) 

744 del exclude_categories 

745 

746 if codec is not None: 

747 try: 

748 codec = codecs.lookup(codec).name 

749 # Check this is not a str-to-str or bytes-to-bytes codec; see 

750 # https://docs.python.org/3/library/codecs.html#binary-transforms 

751 "".encode(codec) 

752 except LookupError: 

753 raise InvalidArgument(f"{codec=} is not valid on this system") from None 

754 except Exception: 

755 raise InvalidArgument(f"{codec=} is not a valid codec") from None 

756 

757 for char in include_characters: 

758 try: 

759 char.encode(encoding=codec, errors="strict") 

760 except UnicodeEncodeError: 

761 raise InvalidArgument( 

762 f"Character {char!r} in {include_characters=} " 

763 f"cannot be encoded with {codec=}" 

764 ) from None 

765 

766 # ascii and utf-8 are sufficient common that we have faster special handling 

767 if codec == "ascii": 

768 if (max_codepoint is None) or (max_codepoint > 127): 

769 max_codepoint = 127 

770 codec = None 

771 elif codec == "utf-8": 

772 if categories is None: 

773 categories = all_categories() 

774 categories = tuple(c for c in categories if c != "Cs") 

775 

776 return OneCharStringStrategy.from_characters_args( 

777 categories=categories, 

778 exclude_characters=exclude_characters, 

779 min_codepoint=min_codepoint, 

780 max_codepoint=max_codepoint, 

781 include_characters=include_characters, 

782 codec=codec, 

783 ) 

784 

785 

786# Hide the deprecated aliases from documentation and casual inspection 

787characters.__signature__ = (__sig := get_signature(characters)).replace( # type: ignore 

788 parameters=[p for p in __sig.parameters.values() if "list" not in p.name] 

789) 

790 

791 

792@cacheable 

793@defines_strategy(force_reusable_values=True) 

794def text( 

795 alphabet: Collection[str] | SearchStrategy[str] = characters(codec="utf-8"), 

796 *, 

797 min_size: int = 0, 

798 max_size: int | None = None, 

799) -> SearchStrategy[str]: 

800 """Generates strings with characters drawn from ``alphabet``, which should 

801 be a collection of length one strings or a strategy generating such strings. 

802 

803 The default alphabet strategy can generate the full unicode range but 

804 excludes surrogate characters because they are invalid in the UTF-8 

805 encoding. You can use :func:`~hypothesis.strategies.characters` without 

806 arguments to find surrogate-related bugs such as :bpo:`34454`. 

807 

808 ``min_size`` and ``max_size`` have the usual interpretations. 

809 Note that Python measures string length by counting codepoints: U+00C5 

810 ``Å`` is a single character, while U+0041 U+030A ``Å`` is two - the ``A``, 

811 and a combining ring above. 

812 

813 Examples from this strategy shrink towards shorter strings, and with the 

814 characters in the text shrinking as per the alphabet strategy. 

815 This strategy does not :func:`~python:unicodedata.normalize` examples, 

816 so generated strings may be in any or none of the 'normal forms'. 

817 """ 

818 check_valid_sizes(min_size, max_size) 

819 if isinstance(alphabet, SearchStrategy): 

820 char_strategy = unwrap_strategies(alphabet) 

821 if isinstance(char_strategy, SampledFromStrategy): 

822 # Check this via the up-front validation logic below, and incidentally 

823 # convert into a `characters()` strategy for standard text shrinking. 

824 return text(char_strategy.elements, min_size=min_size, max_size=max_size) 

825 elif not isinstance(char_strategy, OneCharStringStrategy): 

826 char_strategy = char_strategy.map(_check_is_single_character) 

827 else: 

828 non_string = [c for c in alphabet if not isinstance(c, str)] 

829 if non_string: 

830 raise InvalidArgument( 

831 "The following elements in alphabet are not unicode " 

832 f"strings: {non_string!r}" 

833 ) 

834 not_one_char = [c for c in alphabet if len(c) != 1] 

835 if not_one_char: 

836 raise InvalidArgument( 

837 "The following elements in alphabet are not of length one, " 

838 f"which leads to violation of size constraints: {not_one_char!r}" 

839 ) 

840 if alphabet in ["ascii", "utf-8"]: 

841 warnings.warn( 

842 f"st.text({alphabet!r}): it seems like you are trying to use the " 

843 f"codec {alphabet!r}. st.text({alphabet!r}) instead generates " 

844 f"strings using the literal characters {list(alphabet)!r}. To specify " 

845 f"the {alphabet} codec, use st.text(st.characters(codec={alphabet!r})). " 

846 "If you intended to use character literals, you can silence this " 

847 "warning by reordering the characters.", 

848 HypothesisWarning, 

849 # this stacklevel is of course incorrect, but breaking out of the 

850 # levels of LazyStrategy and validation isn't worthwhile. 

851 stacklevel=1, 

852 ) 

853 char_strategy = ( 

854 characters(categories=(), include_characters=alphabet) 

855 if alphabet 

856 else nothing() 

857 ) 

858 if (max_size == 0 or char_strategy.is_empty) and not min_size: 

859 return just("") 

860 # mypy is unhappy with ListStrategy(SearchStrategy[list[Ex]]) and then TextStrategy 

861 # setting Ex = str. Mypy is correct to complain because we have an LSP violation 

862 # here in the TextStrategy.do_draw override. Would need refactoring to resolve. 

863 return TextStrategy(char_strategy, min_size=min_size, max_size=max_size) # type: ignore 

864 

865 

866@overload 

867def from_regex( 

868 regex: bytes | Pattern[bytes], 

869 *, 

870 fullmatch: bool = False, 

871) -> SearchStrategy[bytes]: # pragma: no cover 

872 ... 

873 

874 

875@overload 

876def from_regex( 

877 regex: str | Pattern[str], 

878 *, 

879 fullmatch: bool = False, 

880 alphabet: str | SearchStrategy[str] = characters(codec="utf-8"), 

881) -> SearchStrategy[str]: # pragma: no cover 

882 ... 

883 

884 

885@cacheable 

886@defines_strategy() 

887def from_regex( 

888 regex: AnyStr | Pattern[AnyStr], 

889 *, 

890 fullmatch: bool = False, 

891 alphabet: str | SearchStrategy[str] | None = None, 

892) -> SearchStrategy[AnyStr]: 

893 r"""Generates strings that contain a match for the given regex (i.e. ones 

894 for which :func:`python:re.search` will return a non-None result). 

895 

896 ``regex`` may be a pattern or :func:`compiled regex <python:re.compile>`. 

897 Both byte-strings and unicode strings are supported, and will generate 

898 examples of the same type. 

899 

900 You can use regex flags such as :obj:`python:re.IGNORECASE` or 

901 :obj:`python:re.DOTALL` to control generation. Flags can be passed either 

902 in compiled regex or inside the pattern with a ``(?iLmsux)`` group. 

903 

904 Some regular expressions are only partly supported - the underlying 

905 strategy checks local matching and relies on filtering to resolve 

906 context-dependent expressions. Using too many of these constructs may 

907 cause health-check errors as too many examples are filtered out. This 

908 mainly includes (positive or negative) lookahead and lookbehind groups. 

909 

910 If you want the generated string to match the whole regex you should use 

911 boundary markers. So e.g. ``r"\A.\Z"`` will return a single character 

912 string, while ``"."`` will return any string, and ``r"\A.$"`` will return 

913 a single character optionally followed by a ``"\n"``. 

914 Alternatively, passing ``fullmatch=True`` will ensure that the whole 

915 string is a match, as if you had used the ``\A`` and ``\Z`` markers. 

916 

917 The ``alphabet=`` argument constrains the characters in the generated 

918 string, as for :func:`text`, and is only supported for unicode strings. 

919 

920 Examples from this strategy shrink towards shorter strings and lower 

921 character values, with exact behaviour that may depend on the pattern. 

922 """ 

923 check_type((str, bytes, re.Pattern), regex, "regex") 

924 check_type(bool, fullmatch, "fullmatch") 

925 pattern = regex.pattern if isinstance(regex, re.Pattern) else regex 

926 if alphabet is not None: 

927 check_type((str, SearchStrategy), alphabet, "alphabet") 

928 if not isinstance(pattern, str): 

929 raise InvalidArgument("alphabet= is not supported for bytestrings") 

930 alphabet = OneCharStringStrategy.from_alphabet(alphabet) 

931 elif isinstance(pattern, str): 

932 alphabet = characters(codec="utf-8") 

933 

934 # TODO: We would like to move this to the top level, but pending some major 

935 # refactoring it's hard to do without creating circular imports. 

936 from hypothesis.strategies._internal.regex import regex_strategy 

937 

938 return regex_strategy(regex, fullmatch, alphabet=alphabet) 

939 

940 

941@cacheable 

942@defines_strategy(force_reusable_values=True) 

943def binary( 

944 *, 

945 min_size: int = 0, 

946 max_size: int | None = None, 

947) -> SearchStrategy[bytes]: 

948 """Generates :class:`python:bytes`. 

949 

950 The generated :class:`python:bytes` will have a length of at least ``min_size`` 

951 and at most ``max_size``. If ``max_size`` is None there is no upper limit. 

952 

953 Examples from this strategy shrink towards smaller strings and lower byte 

954 values. 

955 """ 

956 check_valid_sizes(min_size, max_size) 

957 return BytesStrategy(min_size, max_size) 

958 

959 

960@cacheable 

961@defines_strategy() 

962def randoms( 

963 *, 

964 note_method_calls: bool = False, 

965 use_true_random: bool = False, 

966) -> SearchStrategy[random.Random]: 

967 """Generates instances of ``random.Random``. The generated Random instances 

968 are of a special HypothesisRandom subclass. 

969 

970 - If ``note_method_calls`` is set to ``True``, Hypothesis will print the 

971 randomly drawn values in any falsifying test case. This can be helpful 

972 for debugging the behaviour of randomized algorithms. 

973 - If ``use_true_random`` is set to ``True`` then values will be drawn from 

974 their usual distribution, otherwise they will actually be Hypothesis 

975 generated values (and will be shrunk accordingly for any failing test 

976 case). Setting ``use_true_random=False`` will tend to expose bugs that 

977 would occur with very low probability when it is set to True, and this 

978 flag should only be set to True when your code relies on the distribution 

979 of values for correctness. 

980 

981 For managing global state, see the :func:`~hypothesis.strategies.random_module` 

982 strategy and :func:`~hypothesis.register_random` function. 

983 """ 

984 check_type(bool, note_method_calls, "note_method_calls") 

985 check_type(bool, use_true_random, "use_true_random") 

986 

987 from hypothesis.strategies._internal.random import RandomStrategy 

988 

989 return RandomStrategy( 

990 use_true_random=use_true_random, note_method_calls=note_method_calls 

991 ) 

992 

993 

994class RandomSeeder: 

995 def __init__(self, seed): 

996 self.seed = seed 

997 

998 def __repr__(self): 

999 return f"RandomSeeder({self.seed!r})" 

1000 

1001 

1002class RandomModule(SearchStrategy): 

1003 def do_draw(self, data: ConjectureData) -> RandomSeeder: 

1004 # It would be unsafe to do run this method more than once per test case, 

1005 # because cleanup() runs tasks in FIFO order (at time of writing!). 

1006 # Fortunately, the random_module() strategy wraps us in shared(), so 

1007 # it's cached for all but the first of any number of calls. 

1008 seed = data.draw(integers(0, 2**32 - 1)) 

1009 seed_all, restore_all = get_seeder_and_restorer(seed) 

1010 seed_all() 

1011 cleanup(restore_all) 

1012 return RandomSeeder(seed) 

1013 

1014 

1015@cacheable 

1016@defines_strategy() 

1017def random_module() -> SearchStrategy[RandomSeeder]: 

1018 """Hypothesis always seeds global PRNGs before running a test, and restores the 

1019 previous state afterwards. 

1020 

1021 If having a fixed seed would unacceptably weaken your tests, and you 

1022 cannot use a ``random.Random`` instance provided by 

1023 :func:`~hypothesis.strategies.randoms`, this strategy calls 

1024 :func:`python:random.seed` with an arbitrary integer and passes you 

1025 an opaque object whose repr displays the seed value for debugging. 

1026 If ``numpy.random`` is available, that state is also managed, as is anything 

1027 managed by :func:`hypothesis.register_random`. 

1028 

1029 Examples from these strategy shrink to seeds closer to zero. 

1030 """ 

1031 return shared(RandomModule(), key="hypothesis.strategies.random_module()") 

1032 

1033 

1034class BuildsStrategy(SearchStrategy[Ex]): 

1035 def __init__( 

1036 self, 

1037 target: Callable[..., Ex], 

1038 args: tuple[SearchStrategy[Any], ...], 

1039 kwargs: dict[str, SearchStrategy[Any]], 

1040 ): 

1041 super().__init__() 

1042 self.target = target 

1043 self.args = args 

1044 self.kwargs = kwargs 

1045 

1046 def calc_label(self) -> int: 

1047 return combine_labels( 

1048 self.class_label, 

1049 calc_label_from_callable(self.target), 

1050 *[strat.label for strat in self.args], 

1051 *[calc_label_from_name(k) for k in self.kwargs], 

1052 *[strat.label for strat in self.kwargs.values()], 

1053 ) 

1054 

1055 def do_draw(self, data: ConjectureData) -> Ex: 

1056 context = current_build_context() 

1057 arg_labels: ArgLabelsT = {} 

1058 

1059 args = [] 

1060 for i, s in enumerate(self.args): 

1061 with context.track_arg_label(f"arg[{i}]") as arg_label: 

1062 args.append(data.draw(s)) 

1063 arg_labels |= arg_label 

1064 

1065 kwargs = {} 

1066 for k, v in self.kwargs.items(): 

1067 with context.track_arg_label(k) as arg_label: 

1068 kwargs[k] = data.draw(v) 

1069 arg_labels |= arg_label 

1070 

1071 try: 

1072 obj = self.target(*args, **kwargs) 

1073 except TypeError as err: 

1074 if ( 

1075 isinstance(self.target, type) 

1076 and issubclass(self.target, enum.Enum) 

1077 and not (self.args or self.kwargs) 

1078 ): 

1079 name = self.target.__module__ + "." + self.target.__qualname__ 

1080 raise InvalidArgument( 

1081 f"Calling {name} with no arguments raised an error - " 

1082 f"try using sampled_from({name}) instead of builds({name})" 

1083 ) from err 

1084 if not (self.args or self.kwargs): 

1085 from .types import is_generic_type 

1086 

1087 if isinstance(self.target, NewType) or is_generic_type(self.target): 

1088 raise InvalidArgument( 

1089 f"Calling {self.target!r} with no arguments raised an " 

1090 f"error - try using from_type({self.target!r}) instead " 

1091 f"of builds({self.target!r})" 

1092 ) from err 

1093 if getattr(self.target, "__no_type_check__", None) is True: 

1094 # Note: could use PEP-678 __notes__ here. Migrate over once we're 

1095 # using an `exceptiongroup` backport with support for that. 

1096 raise TypeError( 

1097 "This might be because the @no_type_check decorator prevented " 

1098 "Hypothesis from inferring a strategy for some required arguments." 

1099 ) from err 

1100 raise 

1101 

1102 context.record_call( 

1103 obj, self.target, args=args, kwargs=kwargs, arg_labels=arg_labels 

1104 ) 

1105 return obj 

1106 

1107 def do_validate(self) -> None: 

1108 tuples(*self.args).validate() 

1109 fixed_dictionaries(self.kwargs).validate() 

1110 

1111 def __repr__(self) -> str: 

1112 bits = [get_pretty_function_description(self.target)] 

1113 bits.extend(map(repr, self.args)) 

1114 bits.extend(f"{k}={v!r}" for k, v in self.kwargs.items()) 

1115 return f"builds({', '.join(bits)})" 

1116 

1117 

1118@cacheable 

1119@defines_strategy() 

1120def builds( 

1121 target: Callable[..., Ex], 

1122 /, 

1123 *args: SearchStrategy[Any], 

1124 **kwargs: SearchStrategy[Any] | EllipsisType, 

1125) -> SearchStrategy[Ex]: 

1126 """Generates values by drawing from ``args`` and ``kwargs`` and passing 

1127 them to the callable (provided as the first positional argument) in the 

1128 appropriate argument position. 

1129 

1130 e.g. ``builds(target, integers(), flag=booleans())`` would draw an 

1131 integer ``i`` and a boolean ``b`` and call ``target(i, flag=b)``. 

1132 

1133 If the callable has type annotations, they will be used to infer a strategy 

1134 for required arguments that were not passed to builds. You can also tell 

1135 builds to infer a strategy for an optional argument by passing ``...`` 

1136 (:obj:`python:Ellipsis`) as a keyword argument to builds, instead of a strategy for 

1137 that argument to the callable. 

1138 

1139 If the callable is a class defined with :pypi:`attrs`, missing required 

1140 arguments will be inferred from the attribute on a best-effort basis, 

1141 e.g. by checking :ref:`attrs standard validators <attrs:api-validators>`. 

1142 Dataclasses are handled natively by the inference from type hints. 

1143 

1144 Examples from this strategy shrink by shrinking the argument values to 

1145 the callable. 

1146 """ 

1147 if not callable(target): 

1148 from hypothesis.strategies._internal.types import is_a_union 

1149 

1150 # before 3.14, unions were callable, so it got an error message in 

1151 # BuildsStrategy.do_draw. In 3.14+, unions are not callable, so 

1152 # we error earlier here instead. 

1153 suggestion = ( 

1154 f" Try using from_type({target}) instead?" if is_a_union(target) else "" 

1155 ) 

1156 raise InvalidArgument( 

1157 "The first positional argument to builds() must be a callable " 

1158 f"target to construct.{suggestion}" 

1159 ) 

1160 

1161 if ... in args: # type: ignore # we only annotated the allowed types 

1162 # Avoid an implementation nightmare juggling tuples and worse things 

1163 raise InvalidArgument( 

1164 "... was passed as a positional argument to " 

1165 "builds(), but is only allowed as a keyword arg" 

1166 ) 

1167 required = required_args(target, args, kwargs) 

1168 to_infer = {k for k, v in kwargs.items() if v is ...} 

1169 if required or to_infer: 

1170 if ( 

1171 isinstance(target, type) 

1172 and (attr := sys.modules.get("attr")) is not None 

1173 and attr.has(target) 

1174 ): # pragma: no cover # covered by our attrs tests in check-niche 

1175 # Use our custom introspection for attrs classes 

1176 from hypothesis.strategies._internal.attrs import from_attrs 

1177 

1178 return from_attrs(target, args, kwargs, required | to_infer) 

1179 # Otherwise, try using type hints 

1180 hints = get_type_hints(target) 

1181 if to_infer - set(hints): 

1182 badargs = ", ".join(sorted(to_infer - set(hints))) 

1183 raise InvalidArgument( 

1184 f"passed ... for {badargs}, but we cannot infer a strategy " 

1185 "because these arguments have no type annotation" 

1186 ) 

1187 infer_for = {k: v for k, v in hints.items() if k in (required | to_infer)} 

1188 if infer_for: 

1189 from hypothesis.strategies._internal.types import _global_type_lookup 

1190 

1191 for kw, t in infer_for.items(): 

1192 if t in _global_type_lookup: 

1193 kwargs[kw] = from_type(t) 

1194 else: 

1195 # We defer resolution of these type annotations so that the obvious 

1196 # approach to registering recursive types just works. I.e., 

1197 # if we're inside `register_type_strategy(cls, builds(cls, ...))` 

1198 # and `...` contains recursion on `cls`. See 

1199 # https://github.com/HypothesisWorks/hypothesis/issues/3026 

1200 kwargs[kw] = deferred(lambda t=t: from_type(t)) # type: ignore 

1201 

1202 # validated by handling all EllipsisType in the to_infer case 

1203 kwargs = cast(dict[str, SearchStrategy], kwargs) 

1204 return BuildsStrategy(target, args, kwargs) 

1205 

1206 

1207@cacheable 

1208@defines_strategy(eager=True) 

1209def from_type(thing: type[T]) -> SearchStrategy[T]: 

1210 """Looks up the appropriate search strategy for the given type. 

1211 

1212 |st.from_type| is used internally to fill in missing arguments to 

1213 |st.builds| and can be used interactively 

1214 to explore what strategies are available or to debug type resolution. 

1215 

1216 You can use |st.register_type_strategy| to 

1217 handle your custom types, or to globally redefine certain strategies - 

1218 for example excluding NaN from floats, or use timezone-aware instead of 

1219 naive time and datetime strategies. 

1220 

1221 |st.from_type| looks up a strategy in the following order: 

1222 

1223 1. If ``thing`` is in the default lookup mapping or user-registered lookup, 

1224 return the corresponding strategy. The default lookup covers all types 

1225 with Hypothesis strategies, including extras where possible. 

1226 2. If ``thing`` is from the :mod:`python:typing` module, return the 

1227 corresponding strategy (special logic). 

1228 3. If ``thing`` has one or more subtypes in the merged lookup, return 

1229 the union of the strategies for those types that are not subtypes of 

1230 other elements in the lookup. 

1231 4. Finally, if ``thing`` has type annotations for all required arguments, 

1232 and is not an abstract class, it is resolved via 

1233 |st.builds|. 

1234 5. Because :mod:`abstract types <python:abc>` cannot be instantiated, 

1235 we treat abstract types as the union of their concrete subclasses. 

1236 Note that this lookup works via inheritance but not via 

1237 :obj:`~python:abc.ABCMeta.register`, so you may still need to use 

1238 |st.register_type_strategy|. 

1239 

1240 There is a valuable recipe for leveraging |st.from_type| to generate 

1241 "everything except" values from a specified type. I.e. 

1242 

1243 .. code-block:: python 

1244 

1245 def everything_except(excluded_types): 

1246 return ( 

1247 from_type(type) 

1248 .flatmap(from_type) 

1249 .filter(lambda x: not isinstance(x, excluded_types)) 

1250 ) 

1251 

1252 For example, ``everything_except(int)`` returns a strategy that can 

1253 generate anything that |st.from_type| can ever generate, except for 

1254 instances of |int|, and excluding instances of types 

1255 added via |st.register_type_strategy|. 

1256 

1257 This is useful when writing tests which check that invalid input is 

1258 rejected in a certain way. 

1259 """ 

1260 try: 

1261 with warnings.catch_warnings(): 

1262 warnings.simplefilter("error") 

1263 return _from_type(thing) 

1264 except Exception: 

1265 return _from_type_deferred(thing) 

1266 

1267 

1268def _from_type_deferred(thing: type[Ex]) -> SearchStrategy[Ex]: 

1269 # This tricky little dance is because we want to show the repr of the actual 

1270 # underlying strategy wherever possible, as a form of user education, but 

1271 # would prefer to fall back to the default "from_type(...)" repr instead of 

1272 # "deferred(...)" for recursive types or invalid arguments. 

1273 try: 

1274 thing_repr = nicerepr(thing) 

1275 if hasattr(thing, "__module__"): 

1276 module_prefix = f"{thing.__module__}." 

1277 if not thing_repr.startswith(module_prefix): 

1278 thing_repr = module_prefix + thing_repr 

1279 repr_ = f"from_type({thing_repr})" 

1280 except Exception: # pragma: no cover 

1281 repr_ = None 

1282 return LazyStrategy( 

1283 lambda thing: deferred(lambda: _from_type(thing)), 

1284 (thing,), 

1285 {}, 

1286 force_repr=repr_, 

1287 ) 

1288 

1289 

1290_recurse_guard: ContextVar = ContextVar("recurse_guard") 

1291 

1292 

1293def _from_type(thing: type[Ex]) -> SearchStrategy[Ex]: 

1294 # TODO: We would like to move this to the top level, but pending some major 

1295 # refactoring it's hard to do without creating circular imports. 

1296 from hypothesis.strategies._internal import types 

1297 

1298 def as_strategy(strat_or_callable, thing): 

1299 # User-provided strategies need some validation, and callables even more 

1300 # of it. We do this in three places, hence the helper function 

1301 if not isinstance(strat_or_callable, SearchStrategy): 

1302 assert callable(strat_or_callable) # Validated in register_type_strategy 

1303 strategy = strat_or_callable(thing) 

1304 else: 

1305 strategy = strat_or_callable 

1306 if strategy is NotImplemented: 

1307 return NotImplemented 

1308 if not isinstance(strategy, SearchStrategy): 

1309 raise ResolutionFailed( 

1310 f"Error: {thing} was registered for {nicerepr(strat_or_callable)}, " 

1311 f"but returned non-strategy {strategy!r}" 

1312 ) 

1313 if strategy.is_empty: 

1314 raise ResolutionFailed(f"Error: {thing!r} resolved to an empty strategy") 

1315 return strategy 

1316 

1317 def from_type_guarded(thing): 

1318 """Returns the result of producer, or ... if recursion on thing is encountered""" 

1319 try: 

1320 recurse_guard = _recurse_guard.get() 

1321 except LookupError: 

1322 # We can't simply define the contextvar with default=[], as the 

1323 # default object would be shared across contexts 

1324 _recurse_guard.set(recurse_guard := []) 

1325 if thing in recurse_guard: 

1326 raise RewindRecursive(thing) 

1327 recurse_guard.append(thing) 

1328 try: 

1329 return _from_type(thing) 

1330 except RewindRecursive as rr: 

1331 if rr.target != thing: 

1332 raise 

1333 return ... # defer resolution 

1334 finally: 

1335 recurse_guard.pop() 

1336 

1337 # Let registered extra modules handle their own recognized types first, before 

1338 # e.g. Unions are resolved 

1339 try: 

1340 known = thing in types._global_type_lookup 

1341 except TypeError: 

1342 # thing is not always hashable! 

1343 pass 

1344 else: 

1345 if not known: 

1346 for module, resolver in types._global_extra_lookup.items(): 

1347 if module in sys.modules: 

1348 strat = resolver(thing) 

1349 if strat is not None: 

1350 return strat 

1351 

1352 if isinstance(thing, NewType): 

1353 # Check if we have an explicitly registered strategy for this thing, 

1354 # resolve it so, and otherwise resolve as for the base type. 

1355 if thing in types._global_type_lookup: 

1356 strategy = as_strategy(types._global_type_lookup[thing], thing) 

1357 if strategy is not NotImplemented: 

1358 return strategy 

1359 return _from_type(thing.__supertype__) 

1360 if types.is_a_type_alias_type(thing): # pragma: no cover # covered by 3.12+ tests 

1361 if thing in types._global_type_lookup: 

1362 strategy = as_strategy(types._global_type_lookup[thing], thing) 

1363 if strategy is not NotImplemented: 

1364 return strategy 

1365 return _from_type(thing.__value__) # type: ignore 

1366 if types.is_a_type_alias_type(origin := get_origin(thing)): # pragma: no cover 

1367 # Handle parametrized type aliases like `type A[T] = list[T]; thing = A[int]`. 

1368 # In this case, `thing` is a GenericAlias whose origin is a TypeAliasType. 

1369 # 

1370 # covered by 3.12+ tests. 

1371 if origin in types._global_type_lookup: 

1372 strategy = as_strategy(types._global_type_lookup[origin], thing) 

1373 if strategy is not NotImplemented: 

1374 return strategy 

1375 return _from_type(types.evaluate_type_alias_type(thing)) 

1376 if types.is_a_union(thing): 

1377 args = sorted(thing.__args__, key=types.type_sorting_key) # type: ignore 

1378 return one_of([_from_type(t) for t in args]) 

1379 if thing in types.LiteralStringTypes: # pragma: no cover 

1380 # We can't really cover this because it needs either 

1381 # typing-extensions or python3.11+ typing. 

1382 # `LiteralString` from runtime's point of view is just a string. 

1383 # Fallback to regular text. 

1384 return text() # type: ignore 

1385 

1386 # We also have a special case for TypeVars. 

1387 # They are represented as instances like `~T` when they come here. 

1388 # We need to work with their type instead. 

1389 if isinstance(thing, TypeVar) and type(thing) in types._global_type_lookup: 

1390 strategy = as_strategy(types._global_type_lookup[type(thing)], thing) 

1391 if strategy is not NotImplemented: 

1392 return strategy 

1393 

1394 if not types.is_a_type(thing): 

1395 if isinstance(thing, str): 

1396 # See https://github.com/HypothesisWorks/hypothesis/issues/3016 

1397 raise InvalidArgument( 

1398 f"Got {thing!r} as a type annotation, but the forward-reference " 

1399 "could not be resolved from a string to a type. Consider using " 

1400 "`from __future__ import annotations` instead of forward-reference " 

1401 "strings." 

1402 ) 

1403 raise InvalidArgument(f"{thing=} must be a type") # pragma: no cover 

1404 

1405 if thing in types.NON_RUNTIME_TYPES: 

1406 # Some code like `st.from_type(TypeAlias)` does not make sense. 

1407 # Because there are types in python that do not exist in runtime. 

1408 raise InvalidArgument( 

1409 f"Could not resolve {thing!r} to a strategy, " 

1410 f"because there is no such thing as a runtime instance of {thing!r}" 

1411 ) 

1412 

1413 # Now that we know `thing` is a type, the first step is to check for an 

1414 # explicitly registered strategy. This is the best (and hopefully most 

1415 # common) way to resolve a type to a strategy. Note that the value in the 

1416 # lookup may be a strategy or a function from type -> strategy; and we 

1417 # convert empty results into an explicit error. 

1418 try: 

1419 if thing in types._global_type_lookup: 

1420 strategy = as_strategy(types._global_type_lookup[thing], thing) 

1421 if strategy is not NotImplemented: 

1422 return strategy 

1423 elif ( 

1424 isinstance(thing, GenericAlias) 

1425 and (origin := get_origin(thing)) in types._global_type_lookup 

1426 ): 

1427 strategy = as_strategy(types._global_type_lookup[origin], thing) 

1428 if strategy is not NotImplemented: 

1429 return strategy 

1430 except TypeError: # pragma: no cover 

1431 # This was originally due to a bizarre divergence in behaviour on Python 3.9.0: 

1432 # typing.Callable[[], foo] has __args__ = (foo,) but collections.abc.Callable 

1433 # has __args__ = ([], foo); and as a result is non-hashable. 

1434 # We've kept it because we turn out to have more type errors from... somewhere. 

1435 # FIXME: investigate that, maybe it should be fixed more precisely? 

1436 pass 

1437 

1438 if (hasattr(typing, "_TypedDictMeta") and type(thing) is typing._TypedDictMeta) or ( 

1439 hasattr(types.typing_extensions, "_TypedDictMeta") # type: ignore 

1440 and type(thing) is types.typing_extensions._TypedDictMeta # type: ignore 

1441 ): # pragma: no cover 

1442 

1443 def _get_annotation_arg(key, annotation_type): 

1444 try: 

1445 return get_args(annotation_type)[0] 

1446 except IndexError: 

1447 raise InvalidArgument( 

1448 f"`{key}: {annotation_type.__name__}` is not a valid type annotation" 

1449 ) from None 

1450 

1451 # Taken from `Lib/typing.py` and modified: 

1452 def _get_typeddict_qualifiers(key, annotation_type): 

1453 qualifiers = [] 

1454 annotations = [] 

1455 while True: 

1456 annotation_origin = types.extended_get_origin(annotation_type) 

1457 if annotation_origin is Annotated: 

1458 if annotation_args := get_args(annotation_type): 

1459 annotation_type = annotation_args[0] 

1460 annotations.extend(annotation_args[1:]) 

1461 else: 

1462 break 

1463 elif annotation_origin in types.RequiredTypes: 

1464 qualifiers.append(types.RequiredTypes) 

1465 annotation_type = _get_annotation_arg(key, annotation_type) 

1466 elif annotation_origin in types.NotRequiredTypes: 

1467 qualifiers.append(types.NotRequiredTypes) 

1468 annotation_type = _get_annotation_arg(key, annotation_type) 

1469 elif annotation_origin in types.ReadOnlyTypes: 

1470 qualifiers.append(types.ReadOnlyTypes) 

1471 annotation_type = _get_annotation_arg(key, annotation_type) 

1472 else: 

1473 break 

1474 if annotations: 

1475 annotation_type = Annotated[(annotation_type, *annotations)] 

1476 return set(qualifiers), annotation_type 

1477 

1478 # The __optional_keys__ attribute may or may not be present, but if there's no 

1479 # way to tell and we just have to assume that everything is required. 

1480 # See https://github.com/python/cpython/pull/17214 for details. 

1481 optional = set(getattr(thing, "__optional_keys__", ())) 

1482 required = set( 

1483 getattr(thing, "__required_keys__", get_type_hints(thing).keys()) 

1484 ) 

1485 anns = {} 

1486 for k, v in get_type_hints(thing).items(): 

1487 qualifiers, v = _get_typeddict_qualifiers(k, v) 

1488 # We ignore `ReadOnly` type for now, only unwrap it. 

1489 if types.RequiredTypes in qualifiers: 

1490 optional.discard(k) 

1491 required.add(k) 

1492 if types.NotRequiredTypes in qualifiers: 

1493 optional.add(k) 

1494 required.discard(k) 

1495 

1496 anns[k] = from_type_guarded(v) 

1497 if anns[k] is ...: 

1498 anns[k] = _from_type_deferred(v) 

1499 

1500 if not required.isdisjoint(optional): # pragma: no cover 

1501 # It is impossible to cover, because `typing.py` or `typing-extensions` 

1502 # won't allow creating incorrect TypedDicts, 

1503 # this is just a sanity check from our side. 

1504 raise InvalidArgument( 

1505 f"Required keys overlap with optional keys in a TypedDict:" 

1506 f" {required=}, {optional=}" 

1507 ) 

1508 if ( 

1509 (not anns) 

1510 and thing.__annotations__ 

1511 and ".<locals>." in getattr(thing, "__qualname__", "") 

1512 ): 

1513 raise InvalidArgument("Failed to retrieve type annotations for local type") 

1514 return fixed_dictionaries( # type: ignore 

1515 mapping={k: v for k, v in anns.items() if k in required}, 

1516 optional={k: v for k, v in anns.items() if k in optional}, 

1517 ) 

1518 

1519 # If there's no explicitly registered strategy, maybe a subtype of thing 

1520 # is registered - if so, we can resolve it to the subclass strategy. 

1521 # We'll start by checking if thing is from the typing module, 

1522 # because there are several special cases that don't play well with 

1523 # subclass and instance checks. 

1524 if ( 

1525 isinstance(thing, types.typing_root_type) 

1526 or (isinstance(get_origin(thing), type) and get_args(thing)) 

1527 or isinstance(thing, typing.ForwardRef) 

1528 ): 

1529 return types.from_typing_type(thing) 

1530 

1531 # If it's not from the typing module, we get all registered types that are 

1532 # a subclass of `thing` and are not themselves a subtype of any other such 

1533 # type. For example, `Number -> integers() | floats()`, but bools() is 

1534 # not included because bool is a subclass of int as well as Number. 

1535 strategies = [ 

1536 s 

1537 for s in ( 

1538 as_strategy(v, thing) 

1539 for k, v in sorted(types._global_type_lookup.items(), key=repr) 

1540 if isinstance(k, type) 

1541 and issubclass(k, thing) 

1542 and sum(types.try_issubclass(k, typ) for typ in types._global_type_lookup) 

1543 == 1 

1544 ) 

1545 if s is not NotImplemented 

1546 ] 

1547 if any(not s.is_empty for s in strategies): 

1548 return one_of(strategies) 

1549 

1550 # If we don't have a strategy registered for this type or any subtype, we 

1551 # may be able to fall back on type annotations. 

1552 if issubclass(thing, enum.Enum): 

1553 return sampled_from(thing) 

1554 

1555 # Finally, try to build an instance by calling the type object. Unlike builds(), 

1556 # this block *does* try to infer strategies for arguments with default values. 

1557 # That's because of the semantic different; builds() -> "call this with ..." 

1558 # so we only infer when *not* doing so would be an error; from_type() -> "give 

1559 # me arbitrary instances" so the greater variety is acceptable. 

1560 # And if it's *too* varied, express your opinions with register_type_strategy() 

1561 if not isabstract(thing): 

1562 # If we know that builds(thing) will fail, give a better error message 

1563 required = required_args(thing) 

1564 if required and not ( 

1565 required.issubset(get_type_hints(thing)) 

1566 or ((attr := sys.modules.get("attr")) is not None and attr.has(thing)) 

1567 or is_typed_named_tuple(thing) # weird enough that we have a specific check 

1568 ): 

1569 raise ResolutionFailed( 

1570 f"Could not resolve {thing!r} to a strategy; consider " 

1571 "using register_type_strategy" 

1572 ) 

1573 try: 

1574 hints = get_type_hints(thing) 

1575 params = get_signature(thing).parameters 

1576 except Exception: 

1577 params = {} # type: ignore 

1578 

1579 posonly_args = [] 

1580 kwargs = {} 

1581 for k, p in params.items(): 

1582 if ( 

1583 p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY) 

1584 and k in hints 

1585 and k != "return" 

1586 ): 

1587 ps = from_type_guarded(hints[k]) 

1588 if p.default is not Parameter.empty and ps is not ...: 

1589 ps = just(p.default) | ps 

1590 if p.kind is Parameter.POSITIONAL_ONLY: 

1591 # builds() doesn't infer strategies for positional args, so: 

1592 if ps is ...: # pragma: no cover # rather fiddly to test 

1593 if p.default is Parameter.empty: 

1594 raise ResolutionFailed( 

1595 f"Could not resolve {thing!r} to a strategy; " 

1596 "consider using register_type_strategy" 

1597 ) 

1598 ps = just(p.default) 

1599 posonly_args.append(ps) 

1600 else: 

1601 kwargs[k] = ps 

1602 if ( 

1603 params 

1604 and not (posonly_args or kwargs) 

1605 and not issubclass(thing, BaseException) 

1606 ): 

1607 from_type_repr = repr_call(from_type, (thing,), {}) 

1608 builds_repr = repr_call(builds, (thing,), {}) 

1609 warnings.warn( 

1610 f"{from_type_repr} resolved to {builds_repr}, because we could not " 

1611 "find any (non-varargs) arguments. Use st.register_type_strategy() " 

1612 "to resolve to a strategy which can generate more than one value, " 

1613 "or to silence this warning.", 

1614 SmallSearchSpaceWarning, 

1615 stacklevel=2, 

1616 ) 

1617 return builds(thing, *posonly_args, **kwargs) 

1618 

1619 # And if it's an abstract type, we'll resolve to a union of subclasses instead. 

1620 subclasses = thing.__subclasses__() 

1621 if not subclasses: 

1622 raise ResolutionFailed( 

1623 f"Could not resolve {thing!r} to a strategy, because it is an abstract " 

1624 "type without any subclasses. Consider using register_type_strategy" 

1625 ) 

1626 

1627 subclass_strategies: SearchStrategy = nothing() 

1628 for sc in subclasses: 

1629 try: 

1630 subclass_strategies |= _from_type(sc) 

1631 except Exception: 

1632 pass 

1633 if subclass_strategies.is_empty: 

1634 # We're unable to resolve subclasses now, but we might be able to later - 

1635 # so we'll just go back to the mixed distribution. 

1636 return sampled_from(subclasses).flatmap(_from_type) 

1637 return subclass_strategies 

1638 

1639 

1640@cacheable 

1641@defines_strategy(force_reusable_values=True) 

1642def fractions( 

1643 min_value: Real | str | None = None, 

1644 max_value: Real | str | None = None, 

1645 *, 

1646 max_denominator: int | None = None, 

1647) -> SearchStrategy[Fraction]: 

1648 """Returns a strategy which generates Fractions. 

1649 

1650 If ``min_value`` is not None then all generated values are no less than 

1651 ``min_value``. If ``max_value`` is not None then all generated values are no 

1652 greater than ``max_value``. ``min_value`` and ``max_value`` may be anything accepted 

1653 by the :class:`~fractions.Fraction` constructor. 

1654 

1655 If ``max_denominator`` is not None then the denominator of any generated 

1656 values is no greater than ``max_denominator``. Note that ``max_denominator`` must 

1657 be None or a positive integer. 

1658 

1659 Examples from this strategy shrink towards smaller denominators, then 

1660 closer to zero. 

1661 """ 

1662 min_value = try_convert(Fraction, min_value, "min_value") 

1663 max_value = try_convert(Fraction, max_value, "max_value") 

1664 # These assertions tell Mypy what happened in try_convert 

1665 assert min_value is None or isinstance(min_value, Fraction) 

1666 assert max_value is None or isinstance(max_value, Fraction) 

1667 

1668 check_valid_interval(min_value, max_value, "min_value", "max_value") 

1669 check_valid_integer(max_denominator, "max_denominator") 

1670 

1671 if max_denominator is not None: 

1672 if max_denominator < 1: 

1673 raise InvalidArgument(f"{max_denominator=} must be >= 1") 

1674 if min_value is not None and min_value.denominator > max_denominator: 

1675 raise InvalidArgument( 

1676 f"The {min_value=} has a denominator greater than the " 

1677 f"{max_denominator=}" 

1678 ) 

1679 if max_value is not None and max_value.denominator > max_denominator: 

1680 raise InvalidArgument( 

1681 f"The {max_value=} has a denominator greater than the " 

1682 f"{max_denominator=}" 

1683 ) 

1684 

1685 if min_value is not None and min_value == max_value: 

1686 return just(min_value) 

1687 

1688 def dm_func(denom): 

1689 """Take denom, construct numerator strategy, and build fraction.""" 

1690 # Four cases of algebra to get integer bounds and scale factor. 

1691 min_num, max_num = None, None 

1692 if max_value is None and min_value is None: 

1693 pass 

1694 elif min_value is None: 

1695 max_num = denom * max_value.numerator 

1696 denom *= max_value.denominator 

1697 elif max_value is None: 

1698 min_num = denom * min_value.numerator 

1699 denom *= min_value.denominator 

1700 else: 

1701 low = min_value.numerator * max_value.denominator 

1702 high = max_value.numerator * min_value.denominator 

1703 scale = min_value.denominator * max_value.denominator 

1704 # After calculating our integer bounds and scale factor, we remove 

1705 # the gcd to avoid drawing more bytes for the example than needed. 

1706 # Note that `div` can be at most equal to `scale`. 

1707 div = math.gcd(scale, math.gcd(low, high)) 

1708 min_num = denom * low // div 

1709 max_num = denom * high // div 

1710 denom *= scale // div 

1711 

1712 return builds( 

1713 Fraction, integers(min_value=min_num, max_value=max_num), just(denom) 

1714 ) 

1715 

1716 if max_denominator is None: 

1717 return integers(min_value=1).flatmap(dm_func) 

1718 

1719 return ( 

1720 integers(1, max_denominator) 

1721 .flatmap(dm_func) 

1722 .map(lambda f: f.limit_denominator(max_denominator)) 

1723 ) 

1724 

1725 

1726def _as_finite_decimal( 

1727 value: Real | str | None, name: str, allow_infinity: bool | None, places: int | None 

1728) -> Decimal | None: 

1729 """Convert decimal bounds to decimals, carefully.""" 

1730 assert name in ("min_value", "max_value") 

1731 if value is None: 

1732 return None 

1733 old = value 

1734 if isinstance(value, Fraction): 

1735 value = Context(prec=places).divide(value.numerator, value.denominator) 

1736 if old != value: 

1737 raise InvalidArgument( 

1738 f"{old!r} cannot be exactly represented as a decimal with {places=}" 

1739 ) 

1740 if not isinstance(value, Decimal): 

1741 with localcontext(Context()): # ensure that default traps are enabled 

1742 value = try_convert(Decimal, value, name) 

1743 assert isinstance(value, Decimal) 

1744 if value.is_nan(): 

1745 raise InvalidArgument(f"Invalid {name}={value!r}") 

1746 

1747 # If you are reading this conditional, I am so sorry. I did my best. 

1748 finitude_old = value if isinstance(old, str) else old 

1749 if math.isfinite(finitude_old) != math.isfinite(value) or ( 

1750 value.is_finite() and Fraction(str(old)) != Fraction(str(value)) 

1751 ): 

1752 note_deprecation( 

1753 f"{old!r} cannot be exactly represented as a decimal with {places=}", 

1754 since="2025-11-02", 

1755 has_codemod=False, 

1756 stacklevel=1, 

1757 ) 

1758 

1759 if value.is_finite(): 

1760 return value 

1761 assert value.is_infinite() 

1762 if (value < 0 if "min" in name else value > 0) and allow_infinity is not False: 

1763 return None 

1764 raise InvalidArgument(f"{allow_infinity=}, but {name}={value!r}") 

1765 

1766 

1767@cacheable 

1768@defines_strategy(force_reusable_values=True) 

1769def decimals( 

1770 min_value: Real | str | None = None, 

1771 max_value: Real | str | None = None, 

1772 *, 

1773 allow_nan: bool | None = None, 

1774 allow_infinity: bool | None = None, 

1775 places: int | None = None, 

1776) -> SearchStrategy[Decimal]: 

1777 """Generates instances of :class:`python:decimal.Decimal`, which may be: 

1778 

1779 - A finite rational number, between ``min_value`` and ``max_value``. 

1780 - Not a Number, if ``allow_nan`` is True. None means "allow NaN, unless 

1781 ``min_value`` and ``max_value`` are not None". 

1782 - Positive or negative infinity, if ``max_value`` and ``min_value`` 

1783 respectively are None, and ``allow_infinity`` is not False. None means 

1784 "allow infinity, unless excluded by the min and max values". 

1785 

1786 Note that where floats have one ``NaN`` value, Decimals have four: signed, 

1787 and either *quiet* or *signalling*. See `the decimal module docs 

1788 <https://docs.python.org/3/library/decimal.html#special-values>`_ for 

1789 more information on special values. 

1790 

1791 If ``places`` is not None, all finite values drawn from the strategy will 

1792 have that number of digits after the decimal place. 

1793 

1794 Examples from this strategy do not have a well defined shrink order but 

1795 try to maximize human readability when shrinking. 

1796 """ 

1797 # Convert min_value and max_value to Decimal values, and validate args 

1798 check_valid_integer(places, "places") 

1799 if places is not None and places < 0: 

1800 raise InvalidArgument(f"{places=} may not be negative") 

1801 min_value = _as_finite_decimal(min_value, "min_value", allow_infinity, places) 

1802 max_value = _as_finite_decimal(max_value, "max_value", allow_infinity, places) 

1803 check_valid_interval(min_value, max_value, "min_value", "max_value") 

1804 if allow_infinity and (None not in (min_value, max_value)): 

1805 raise InvalidArgument("Cannot allow infinity between finite bounds") 

1806 # Set up a strategy for finite decimals. Note that both floating and 

1807 # fixed-point decimals require careful handling to remain isolated from 

1808 # any external precision context - in short, we always work out the 

1809 # required precision for lossless operation and use context methods. 

1810 if places is not None: 

1811 # Fixed-point decimals are basically integers with a scale factor 

1812 def ctx(val): 

1813 """Return a context in which this value is lossless.""" 

1814 precision = ceil(math.log10(abs(val) or 1)) + places + 1 

1815 return Context(prec=max([precision, 1])) 

1816 

1817 def int_to_decimal(val): 

1818 context = ctx(val) 

1819 return context.quantize(context.multiply(val, factor), factor) 

1820 

1821 factor = Decimal(10) ** -places 

1822 min_num, max_num = None, None 

1823 if min_value is not None: 

1824 min_num = ceil(ctx(min_value).divide(min_value, factor)) 

1825 if max_value is not None: 

1826 max_num = floor(ctx(max_value).divide(max_value, factor)) 

1827 if min_num is not None and max_num is not None and min_num > max_num: 

1828 raise InvalidArgument( 

1829 f"There are no decimals with {places} places between " 

1830 f"{min_value=} and {max_value=}" 

1831 ) 

1832 strat = integers(min_num, max_num).map(int_to_decimal) 

1833 else: 

1834 # Otherwise, they're like fractions featuring a power of ten 

1835 def fraction_to_decimal(val): 

1836 precision = ( 

1837 ceil(math.log10(abs(val.numerator) or 1) + math.log10(val.denominator)) 

1838 + 1 

1839 ) 

1840 return Context(prec=precision or 1).divide( 

1841 Decimal(val.numerator), val.denominator 

1842 ) 

1843 

1844 strat = fractions(min_value, max_value).map(fraction_to_decimal) 

1845 # Compose with sampled_from for infinities and NaNs as appropriate 

1846 special: list[Decimal] = [] 

1847 if allow_infinity or (allow_infinity is None and max_value is None): 

1848 special.append(Decimal("Infinity")) 

1849 if allow_infinity or (allow_infinity is None and min_value is None): 

1850 special.append(Decimal("-Infinity")) 

1851 if allow_nan or (allow_nan is None and (None in (min_value, max_value))): 

1852 special.extend(map(Decimal, ("NaN", "-NaN", "sNaN", "-sNaN"))) 

1853 return strat | (sampled_from(special) if special else nothing()) 

1854 

1855 

1856@defines_strategy(eager=True) 

1857def recursive( 

1858 base: SearchStrategy[Ex], 

1859 extend: Callable[[SearchStrategy[Any]], SearchStrategy[T]], 

1860 *, 

1861 min_leaves: int | None = None, 

1862 max_leaves: int = 100, 

1863) -> SearchStrategy[T | Ex]: 

1864 """base: A strategy to start from. 

1865 

1866 extend: A function which takes a strategy and returns a new strategy. 

1867 

1868 min_leaves: The minimum number of elements to be drawn from base on a given run. 

1869 

1870 max_leaves: The maximum number of elements to be drawn from base on a given run. 

1871 

1872 This returns a strategy ``S`` such that ``S = extend(base | S)``. That is, 

1873 values may be drawn from base, or from any strategy reachable by mixing 

1874 applications of | and extend. 

1875 

1876 An example may clarify: ``recursive(booleans(), lists)`` would return a 

1877 strategy that may return arbitrarily nested and mixed lists of booleans. 

1878 So e.g. ``False``, ``[True]``, ``[False, []]``, and ``[[[[True]]]]`` are 

1879 all valid values to be drawn from that strategy. 

1880 

1881 Examples from this strategy shrink by trying to reduce the amount of 

1882 recursion and by shrinking according to the shrinking behaviour of base 

1883 and the result of extend. 

1884 """ 

1885 return RecursiveStrategy(base, extend, min_leaves, max_leaves) 

1886 

1887 

1888class PermutationStrategy(SearchStrategy): 

1889 def __init__(self, values): 

1890 super().__init__() 

1891 self.values = values 

1892 

1893 def do_draw(self, data): 

1894 # Reversed Fisher-Yates shuffle: swap each element with itself or with 

1895 # a later element. This shrinks i==j for each element, i.e. to no 

1896 # change. We don't consider the last element as it's always a no-op. 

1897 result = list(self.values) 

1898 for i in range(len(result) - 1): 

1899 j = data.draw_integer(i, len(result) - 1) 

1900 result[i], result[j] = result[j], result[i] 

1901 return result 

1902 

1903 

1904@defines_strategy() 

1905def permutations(values: Sequence[T]) -> SearchStrategy[list[T]]: 

1906 """Return a strategy which returns permutations of the ordered collection 

1907 ``values``. 

1908 

1909 Examples from this strategy shrink by trying to become closer to the 

1910 original order of values. 

1911 """ 

1912 values = check_sample(values, "permutations") 

1913 if not values: 

1914 return builds(list) 

1915 

1916 return PermutationStrategy(values) 

1917 

1918 

1919class CompositeStrategy(SearchStrategy): 

1920 def __init__(self, definition, args, kwargs): 

1921 super().__init__() 

1922 self.definition = definition 

1923 self.args = args 

1924 self.kwargs = kwargs 

1925 

1926 def do_draw(self, data): 

1927 return self.definition(data.draw, *self.args, **self.kwargs) 

1928 

1929 def calc_label(self) -> int: 

1930 return combine_labels( 

1931 self.class_label, 

1932 calc_label_from_callable(self.definition), 

1933 ) 

1934 

1935 

1936class DrawFn(Protocol): 

1937 """This type only exists so that you can write type hints for functions 

1938 decorated with :func:`@composite <hypothesis.strategies.composite>`. 

1939 

1940 .. code-block:: python 

1941 

1942 def draw(strategy: SearchStrategy[Ex], label: object = None) -> Ex: ... 

1943 

1944 @composite 

1945 def list_and_index(draw: DrawFn) -> tuple[int, str]: 

1946 i = draw(integers()) # type of `i` inferred as 'int' 

1947 s = draw(text()) # type of `s` inferred as 'str' 

1948 return i, s 

1949 """ 

1950 

1951 def __init__(self): 

1952 raise TypeError("Protocols cannot be instantiated") # pragma: no cover 

1953 

1954 # Protocol overrides our signature for __init__, 

1955 # so we override it right back to make the docs look nice. 

1956 __signature__: Signature = Signature(parameters=[]) 

1957 

1958 # We define this as a callback protocol because a simple typing.Callable is 

1959 # insufficient to fully represent the interface, due to the optional `label` 

1960 # parameter. 

1961 def __call__(self, strategy: SearchStrategy[Ex], label: object = None) -> Ex: 

1962 raise NotImplementedError 

1963 

1964 

1965def _composite(f): 

1966 # Wrapped below, using ParamSpec if available 

1967 if isinstance(f, (classmethod, staticmethod)): 

1968 special_method = type(f) 

1969 f = f.__func__ 

1970 else: 

1971 special_method = None 

1972 

1973 sig = get_signature(f) 

1974 params = tuple(sig.parameters.values()) 

1975 

1976 if not (params and "POSITIONAL" in params[0].kind.name): 

1977 raise InvalidArgument( 

1978 "Functions wrapped with composite must take at least one " 

1979 "positional argument." 

1980 ) 

1981 if params[0].default is not sig.empty: 

1982 raise InvalidArgument("A default value for initial argument will never be used") 

1983 if not (f is typing._overload_dummy or is_first_param_referenced_in_function(f)): 

1984 note_deprecation( 

1985 "There is no reason to use @st.composite on a function which " 

1986 "does not call the provided draw() function internally.", 

1987 since="2022-07-17", 

1988 has_codemod=False, 

1989 ) 

1990 if get_origin(sig.return_annotation) is SearchStrategy: 

1991 ret_repr = repr(sig.return_annotation).replace("hypothesis.strategies.", "st.") 

1992 warnings.warn( 

1993 f"Return-type annotation is `{ret_repr}`, but the decorated " 

1994 "function should return a value (not a strategy)", 

1995 HypothesisWarning, 

1996 stacklevel=3, 

1997 ) 

1998 if params[0].kind.name != "VAR_POSITIONAL": 

1999 params = params[1:] 

2000 newsig = sig.replace( 

2001 parameters=params, 

2002 return_annotation=( 

2003 SearchStrategy 

2004 if sig.return_annotation is sig.empty 

2005 else SearchStrategy[sig.return_annotation] 

2006 ), 

2007 ) 

2008 

2009 @defines_strategy() 

2010 @define_function_signature(f.__name__, f.__doc__, newsig) 

2011 def accept(*args, **kwargs): 

2012 return CompositeStrategy(f, args, kwargs) 

2013 

2014 accept.__module__ = f.__module__ 

2015 accept.__signature__ = newsig 

2016 if special_method is not None: 

2017 return special_method(accept) 

2018 return accept 

2019 

2020 

2021composite_doc = """ 

2022Defines a strategy that is built out of potentially arbitrarily many other 

2023strategies. 

2024 

2025@composite provides a callable ``draw`` as the first parameter to the decorated 

2026function, which can be used to dynamically draw a value from any strategy. For 

2027example: 

2028 

2029.. code-block:: python 

2030 

2031 from hypothesis import strategies as st, given 

2032 

2033 @st.composite 

2034 def values(draw): 

2035 n1 = draw(st.integers()) 

2036 n2 = draw(st.integers(min_value=n1)) 

2037 return (n1, n2) 

2038 

2039 @given(values()) 

2040 def f(value): 

2041 (n1, n2) = value 

2042 assert n1 <= n2 

2043 

2044@composite cannot mix test code and generation code. If you need that, use 

2045|st.data|. 

2046 

2047If :func:`@composite <hypothesis.strategies.composite>` is used to decorate a 

2048method or classmethod, the ``draw`` argument must come before ``self`` or 

2049``cls``. While we therefore recommend writing strategies as standalone functions 

2050and using |st.register_type_strategy| to associate them with a class, methods 

2051are supported and the ``@composite`` decorator may be applied either before or 

2052after ``@classmethod`` or ``@staticmethod``. See :issue:`2578` and :pull:`2634` 

2053for more details. 

2054 

2055Examples from this strategy shrink by shrinking the output of each draw call. 

2056""" 

2057if typing.TYPE_CHECKING or ParamSpec is not None: 

2058 P = ParamSpec("P") 

2059 

2060 def composite( 

2061 f: Callable[Concatenate[DrawFn, P], Ex], 

2062 ) -> Callable[P, SearchStrategy[Ex]]: 

2063 return _composite(f) 

2064 

2065else: # pragma: no cover 

2066 

2067 @cacheable 

2068 def composite(f: Callable[..., Ex]) -> Callable[..., SearchStrategy[Ex]]: 

2069 return _composite(f) 

2070 

2071 

2072composite.__doc__ = composite_doc 

2073 

2074 

2075@defines_strategy(force_reusable_values=True) 

2076@cacheable 

2077def complex_numbers( 

2078 *, 

2079 min_magnitude: Real = 0, 

2080 max_magnitude: Real | None = None, 

2081 allow_infinity: bool | None = None, 

2082 allow_nan: bool | None = None, 

2083 allow_subnormal: bool = True, 

2084 width: Literal[32, 64, 128] = 128, 

2085) -> SearchStrategy[complex]: 

2086 """Returns a strategy that generates :class:`~python:complex` 

2087 numbers. 

2088 

2089 This strategy draws complex numbers with constrained magnitudes. 

2090 The ``min_magnitude`` and ``max_magnitude`` parameters should be 

2091 non-negative :class:`~python:numbers.Real` numbers; a value 

2092 of ``None`` corresponds an infinite upper bound. 

2093 

2094 If ``min_magnitude`` is nonzero or ``max_magnitude`` is finite, it 

2095 is an error to enable ``allow_nan``. If ``max_magnitude`` is finite, 

2096 it is an error to enable ``allow_infinity``. 

2097 

2098 ``allow_infinity``, ``allow_nan``, and ``allow_subnormal`` are 

2099 applied to each part of the complex number separately, as for 

2100 :func:`~hypothesis.strategies.floats`. 

2101 

2102 The magnitude constraints are respected up to a relative error 

2103 of (around) floating-point epsilon, due to implementation via 

2104 the system ``sqrt`` function. 

2105 

2106 The ``width`` argument specifies the maximum number of bits of precision 

2107 required to represent the entire generated complex number. 

2108 Valid values are 32, 64 or 128, which correspond to the real and imaginary 

2109 components each having width 16, 32 or 64, respectively. 

2110 Passing ``width=64`` will still use the builtin 128-bit 

2111 :class:`~python:complex` class, but always for values which can be 

2112 exactly represented as two 32-bit floats. 

2113 

2114 Examples from this strategy shrink by shrinking their real and 

2115 imaginary parts, as :func:`~hypothesis.strategies.floats`. 

2116 

2117 If you need to generate complex numbers with particular real and 

2118 imaginary parts or relationships between parts, consider using 

2119 :func:`builds(complex, ...) <hypothesis.strategies.builds>` or 

2120 :func:`@composite <hypothesis.strategies.composite>` respectively. 

2121 """ 

2122 check_valid_magnitude(min_magnitude, "min_magnitude") 

2123 check_valid_magnitude(max_magnitude, "max_magnitude") 

2124 check_valid_interval(min_magnitude, max_magnitude, "min_magnitude", "max_magnitude") 

2125 if max_magnitude == math.inf: 

2126 max_magnitude = None 

2127 

2128 if allow_infinity is None: 

2129 allow_infinity = bool(max_magnitude is None) 

2130 elif allow_infinity and max_magnitude is not None: 

2131 raise InvalidArgument(f"Cannot have {allow_infinity=} with {max_magnitude=}") 

2132 if allow_nan is None: 

2133 allow_nan = bool(min_magnitude == 0 and max_magnitude is None) 

2134 elif allow_nan and not (min_magnitude == 0 and max_magnitude is None): 

2135 raise InvalidArgument( 

2136 f"Cannot have {allow_nan=}, {min_magnitude=}, {max_magnitude=}" 

2137 ) 

2138 check_type(bool, allow_subnormal, "allow_subnormal") 

2139 if width not in (32, 64, 128): 

2140 raise InvalidArgument( 

2141 f"{width=}, but must be 32, 64 or 128 (other complex dtypes " 

2142 "such as complex192 or complex256 are not supported)" 

2143 # For numpy, these types would be supported (but not by CPython): 

2144 # https://numpy.org/doc/stable/reference/arrays.scalars.html#complex-floating-point-types 

2145 ) 

2146 component_width = width // 2 

2147 allow_kw = { 

2148 "allow_nan": allow_nan, 

2149 "allow_infinity": allow_infinity, 

2150 # If we have a nonzero normal min_magnitude and draw a zero imaginary part, 

2151 # then allow_subnormal=True would be an error with the min_value to the floats() 

2152 # strategy for the real part. We therefore replace True with None. 

2153 "allow_subnormal": None if allow_subnormal else allow_subnormal, 

2154 "width": component_width, 

2155 } 

2156 

2157 if min_magnitude == 0 and max_magnitude is None: 

2158 # In this simple but common case, there are no constraints on the 

2159 # magnitude and therefore no relationship between the real and 

2160 # imaginary parts. 

2161 return builds(complex, floats(**allow_kw), floats(**allow_kw)) # type: ignore 

2162 

2163 @composite 

2164 def constrained_complex(draw): 

2165 # We downcast drawn floats to the desired (component) width so we 

2166 # guarantee the resulting complex values are representable. Note 

2167 # truncating the mantissa bits with float_of() cannot increase the 

2168 # magnitude of a float, so we are guaranteed to stay within the allowed 

2169 # range. See https://github.com/HypothesisWorks/hypothesis/issues/3573 

2170 

2171 # Draw the imaginary part, and determine the maximum real part given 

2172 # this and the max_magnitude 

2173 if max_magnitude is None: 

2174 zi = draw(floats(**allow_kw)) 

2175 rmax = None 

2176 else: 

2177 zi = draw( 

2178 floats( 

2179 -float_of(max_magnitude, component_width), 

2180 float_of(max_magnitude, component_width), 

2181 **allow_kw, 

2182 ) 

2183 ) 

2184 rmax = float_of(cathetus(max_magnitude, zi), component_width) 

2185 # Draw the real part from the allowed range given the imaginary part 

2186 if min_magnitude == 0 or math.fabs(zi) >= min_magnitude: 

2187 zr = draw(floats(None if rmax is None else -rmax, rmax, **allow_kw)) 

2188 else: 

2189 rmin = float_of(cathetus(min_magnitude, zi), component_width) 

2190 zr = draw(floats(rmin, rmax, **allow_kw)) 

2191 # Order of conditions carefully tuned so that for a given pair of 

2192 # magnitude arguments, we always either draw or do not draw the bool 

2193 # (crucial for good shrinking behaviour) but only invert when needed. 

2194 if min_magnitude > 0 and draw(booleans()) and math.fabs(zi) <= min_magnitude: 

2195 zr = -zr 

2196 return complex(zr, zi) 

2197 

2198 return constrained_complex() 

2199 

2200 

2201@defines_strategy(eager=True) 

2202def shared( 

2203 base: SearchStrategy[Ex], 

2204 *, 

2205 key: Hashable | None = None, 

2206) -> SearchStrategy[Ex]: 

2207 """Returns a strategy that draws a single shared value per run, drawn from 

2208 base. Any two shared instances with the same key will share the same value, 

2209 otherwise the identity of this strategy will be used. That is: 

2210 

2211 >>> s = integers() # or any other strategy 

2212 >>> x = shared(s) 

2213 >>> y = shared(s) 

2214 

2215 In the above x and y may draw different (or potentially the same) values. 

2216 In the following they will always draw the same: 

2217 

2218 >>> x = shared(s, key="hi") 

2219 >>> y = shared(s, key="hi") 

2220 

2221 Examples from this strategy shrink as per their base strategy. 

2222 """ 

2223 return SharedStrategy(base, key) 

2224 

2225 

2226@composite 

2227def _maybe_nil_uuids(draw, uuid): 

2228 # Equivalent to `random_uuids | just(...)`, with a stronger bias to the former. 

2229 if draw(data()).conjecture_data.draw_boolean(1 / 64): 

2230 return UUID("00000000-0000-0000-0000-000000000000") 

2231 return uuid 

2232 

2233 

2234@cacheable 

2235@defines_strategy(force_reusable_values=True) 

2236def uuids( 

2237 *, version: Literal[1, 2, 3, 4, 5] | None = None, allow_nil: bool = False 

2238) -> SearchStrategy[UUID]: 

2239 """Returns a strategy that generates :class:`UUIDs <uuid.UUID>`. 

2240 

2241 If the optional version argument is given, value is passed through 

2242 to :class:`~python:uuid.UUID` and only UUIDs of that version will 

2243 be generated. 

2244 

2245 If ``allow_nil`` is True, generate the nil UUID much more often. 

2246 Otherwise, all returned values from this will be unique, so e.g. if you do 

2247 ``lists(uuids())`` the resulting list will never contain duplicates. 

2248 

2249 Examples from this strategy don't have any meaningful shrink order. 

2250 """ 

2251 check_type(bool, allow_nil, "allow_nil") 

2252 if version not in (None, 1, 2, 3, 4, 5): 

2253 raise InvalidArgument( 

2254 f"{version=}, but version must be in " 

2255 "(None, 1, 2, 3, 4, 5) to pass to the uuid.UUID constructor." 

2256 ) 

2257 random_uuids = shared( 

2258 randoms(use_true_random=True), key="hypothesis.strategies.uuids.generator" 

2259 ).map(lambda r: UUID(version=version, int=r.getrandbits(128))) 

2260 

2261 if allow_nil: 

2262 if version is not None: 

2263 raise InvalidArgument("The nil UUID is not of any version") 

2264 return random_uuids.flatmap(_maybe_nil_uuids) 

2265 return random_uuids 

2266 

2267 

2268class RunnerStrategy(SearchStrategy): 

2269 def __init__(self, default): 

2270 super().__init__() 

2271 self.default = default 

2272 

2273 def do_draw(self, data): 

2274 if data.hypothesis_runner is not_set: 

2275 if self.default is not_set: 

2276 raise InvalidArgument( 

2277 "Cannot use runner() strategy with no " 

2278 "associated runner or explicit default." 

2279 ) 

2280 return self.default 

2281 return data.hypothesis_runner 

2282 

2283 

2284@defines_strategy(force_reusable_values=True) 

2285def runner(*, default: Any = not_set) -> SearchStrategy[Any]: 

2286 """A strategy for getting "the current test runner", whatever that may be. 

2287 The exact meaning depends on the entry point, but it will usually be the 

2288 associated 'self' value for it. 

2289 

2290 If you are using this in a rule for stateful testing, this strategy 

2291 will return the instance of the :class:`~hypothesis.stateful.RuleBasedStateMachine` 

2292 that the rule is running for. 

2293 

2294 If there is no current test runner and a default is provided, return 

2295 that default. If no default is provided, raises InvalidArgument. 

2296 

2297 Examples from this strategy do not shrink (because there is only one). 

2298 """ 

2299 return RunnerStrategy(default) 

2300 

2301 

2302class DataObject: 

2303 """This type only exists so that you can write type hints for tests using 

2304 the :func:`~hypothesis.strategies.data` strategy. Do not use it directly! 

2305 """ 

2306 

2307 # Note that "only exists" here really means "is only exported to users", 

2308 # but we want to treat it as "semi-stable", not document it as "public API". 

2309 

2310 def __init__(self, data: ConjectureData) -> None: 

2311 self.count = 0 

2312 self.conjecture_data = data 

2313 

2314 __signature__ = Signature() # hide internals from Sphinx introspection 

2315 

2316 def __repr__(self) -> str: 

2317 return "data(...)" 

2318 

2319 def draw(self, strategy: SearchStrategy[Ex], label: Any = None) -> Ex: 

2320 """Like :obj:`~hypothesis.strategies.DrawFn`.""" 

2321 check_strategy(strategy, "strategy") 

2322 self.count += 1 

2323 desc = f"Draw {self.count}{'' if label is None else f' ({label})'}" 

2324 with deprecate_random_in_strategy("{}from {!r}", desc, strategy): 

2325 result = self.conjecture_data.draw(strategy, observe_as=f"generate:{desc}") 

2326 

2327 # optimization to avoid needless printer.pretty 

2328 if should_note(): 

2329 printer = RepresentationPrinter(context=current_build_context()) 

2330 printer.text(f"{desc}: ") 

2331 if self.conjecture_data.provider.avoid_realization: 

2332 printer.text("<symbolic>") 

2333 else: 

2334 printer.pretty(result) 

2335 note(printer.getvalue()) 

2336 return result 

2337 

2338 

2339class DataStrategy(SearchStrategy): 

2340 def do_draw(self, data): 

2341 if data._shared_data_strategy is None: 

2342 data._shared_data_strategy = DataObject(data) 

2343 return data._shared_data_strategy 

2344 

2345 def __repr__(self) -> str: 

2346 return "data()" 

2347 

2348 def map(self, f): 

2349 self.__not_a_first_class_strategy("map") 

2350 

2351 def filter(self, condition: Callable[[Ex], Any]) -> NoReturn: 

2352 self.__not_a_first_class_strategy("filter") 

2353 

2354 def flatmap(self, f): 

2355 self.__not_a_first_class_strategy("flatmap") 

2356 

2357 def example(self) -> NoReturn: 

2358 self.__not_a_first_class_strategy("example") 

2359 

2360 def __not_a_first_class_strategy(self, name: str) -> NoReturn: 

2361 raise InvalidArgument( 

2362 f"Cannot call {name} on a DataStrategy. You should probably " 

2363 "be using @composite for whatever it is you're trying to do." 

2364 ) 

2365 

2366 

2367@cacheable 

2368@defines_strategy(eager=True) 

2369def data() -> SearchStrategy[DataObject]: 

2370 """ 

2371 Provides an object ``data`` with a ``data.draw`` function which acts like 

2372 the ``draw`` callable provided by |st.composite|, in that it can be used 

2373 to dynamically draw values from strategies. |st.data| is more powerful 

2374 than |st.composite|, because it allows you to mix generation and test code. 

2375 

2376 Here's an example of dynamically generating values using |st.data|: 

2377 

2378 .. code-block:: python 

2379 

2380 from hypothesis import strategies as st, given 

2381 

2382 @given(st.data()) 

2383 def test_values(data): 

2384 n1 = data.draw(st.integers()) 

2385 n2 = data.draw(st.integers(min_value=n1)) 

2386 assert n1 + 1 <= n2 

2387 

2388 If the test fails, each draw will be printed with the falsifying example. 

2389 e.g. the above is wrong (it has a boundary condition error), so will print: 

2390 

2391 .. code-block:: pycon 

2392 

2393 Falsifying example: test_values(data=data(...)) 

2394 Draw 1: 0 

2395 Draw 2: 0 

2396 

2397 Optionally, you can provide a label to identify values generated by each call 

2398 to ``data.draw()``. These labels can be used to identify values in the 

2399 output of a falsifying example. 

2400 

2401 For instance: 

2402 

2403 .. code-block:: python 

2404 

2405 @given(st.data()) 

2406 def test_draw_sequentially(data): 

2407 x = data.draw(st.integers(), label="First number") 

2408 y = data.draw(st.integers(min_value=x), label="Second number") 

2409 assert x < y 

2410 

2411 will produce: 

2412 

2413 .. code-block:: pycon 

2414 

2415 Falsifying example: test_draw_sequentially(data=data(...)) 

2416 Draw 1 (First number): 0 

2417 Draw 2 (Second number): 0 

2418 

2419 Examples from this strategy shrink by shrinking the output of each draw call. 

2420 """ 

2421 return DataStrategy() 

2422 

2423 

2424if sys.version_info < (3, 12): 

2425 # TypeAliasType is new in 3.12 

2426 RegisterTypeT: TypeAlias = type[Ex] 

2427else: # pragma: no cover # covered by test_mypy.py 

2428 from typing import TypeAliasType 

2429 

2430 # see https://github.com/HypothesisWorks/hypothesis/issues/4410 

2431 RegisterTypeT: TypeAlias = type[Ex] | TypeAliasType 

2432 

2433 

2434def register_type_strategy( 

2435 custom_type: RegisterTypeT, 

2436 strategy: SearchStrategy[Ex] | Callable[[type[Ex]], SearchStrategy[Ex]], 

2437) -> None: 

2438 """Add an entry to the global type-to-strategy lookup. 

2439 

2440 This lookup is used in :func:`~hypothesis.strategies.builds` and 

2441 |@given|. 

2442 

2443 :func:`~hypothesis.strategies.builds` will be used automatically for 

2444 classes with type annotations on ``__init__`` , so you only need to 

2445 register a strategy if one or more arguments need to be more tightly 

2446 defined than their type-based default, or if you want to supply a strategy 

2447 for an argument with a default value. 

2448 

2449 ``strategy`` may be a search strategy, or a function that takes a type and 

2450 returns a strategy (useful for generic types). The function may return 

2451 :data:`NotImplemented` to conditionally not provide a strategy for the type 

2452 (the type will still be resolved by other methods, if possible, as if the 

2453 function was not registered). 

2454 

2455 Note that you may not register a parametrised generic type (such as 

2456 ``MyCollection[int]``) directly, because the resolution logic does not 

2457 handle this case correctly. Instead, you may register a *function* for 

2458 ``MyCollection`` and `inspect the type parameters within that function 

2459 <https://stackoverflow.com/q/48572831>`__. 

2460 """ 

2461 # TODO: We would like to move this to the top level, but pending some major 

2462 # refactoring it's hard to do without creating circular imports. 

2463 from hypothesis.strategies._internal import types 

2464 

2465 if not types.is_a_type(custom_type): 

2466 raise InvalidArgument(f"{custom_type=} must be a type") 

2467 if custom_type in types.NON_RUNTIME_TYPES: 

2468 raise InvalidArgument( 

2469 f"{custom_type=} is not allowed to be registered, " 

2470 f"because there is no such thing as a runtime instance of {custom_type!r}" 

2471 ) 

2472 if not (isinstance(strategy, SearchStrategy) or callable(strategy)): 

2473 raise InvalidArgument( 

2474 f"{strategy=} must be a SearchStrategy, or a function that takes " 

2475 "a generic type and returns a specific SearchStrategy" 

2476 ) 

2477 if isinstance(strategy, SearchStrategy): 

2478 with warnings.catch_warnings(): 

2479 warnings.simplefilter("error", HypothesisSideeffectWarning) 

2480 

2481 # Calling is_empty forces materialization of lazy strategies. If this is done at import 

2482 # time, lazy strategies will warn about it; here, we force that warning to raise to 

2483 # avoid the materialization. Ideally, we'd just check if the strategy is lazy, but the 

2484 # lazy strategy may be wrapped underneath another strategy so that's complicated. 

2485 try: 

2486 if strategy.is_empty: 

2487 raise InvalidArgument(f"{strategy=} must not be empty") 

2488 except HypothesisSideeffectWarning: # pragma: no cover 

2489 pass 

2490 if types.has_type_arguments(custom_type): 

2491 raise InvalidArgument( 

2492 f"Cannot register generic type {custom_type!r}, because it has type " 

2493 "arguments which would not be handled. Instead, register a function " 

2494 f"for {get_origin(custom_type)!r} which can inspect specific type " 

2495 "objects and return a strategy." 

2496 ) 

2497 if ( 

2498 "pydantic.generics" in sys.modules 

2499 and isinstance(custom_type, type) 

2500 and issubclass(custom_type, sys.modules["pydantic.generics"].GenericModel) 

2501 and not re.search(r"[A-Za-z_]+\[.+\]", repr(custom_type)) 

2502 and callable(strategy) 

2503 ): # pragma: no cover 

2504 # See https://github.com/HypothesisWorks/hypothesis/issues/2940 

2505 raise InvalidArgument( 

2506 f"Cannot register a function for {custom_type!r}, because parametrized " 

2507 "`pydantic.generics.GenericModel` subclasses aren't actually generic " 

2508 "types at runtime. In this case, you should register a strategy " 

2509 "directly for each parametrized form that you anticipate using." 

2510 ) 

2511 

2512 types._global_type_lookup[custom_type] = strategy 

2513 from_type.__clear_cache() # type: ignore 

2514 

2515 

2516@cacheable 

2517@defines_strategy(eager=True) 

2518def deferred(definition: Callable[[], SearchStrategy[Ex]]) -> SearchStrategy[Ex]: 

2519 """A deferred strategy allows you to write a strategy that references other 

2520 strategies that have not yet been defined. This allows for the easy 

2521 definition of recursive and mutually recursive strategies. 

2522 

2523 The definition argument should be a zero-argument function that returns a 

2524 strategy. It will be evaluated the first time the strategy is used to 

2525 produce an example. 

2526 

2527 Example usage: 

2528 

2529 >>> import hypothesis.strategies as st 

2530 >>> x = st.deferred(lambda: st.booleans() | st.tuples(x, x)) 

2531 >>> x.example() 

2532 (((False, (True, True)), (False, True)), (True, True)) 

2533 >>> x.example() 

2534 True 

2535 

2536 Mutual recursion also works fine: 

2537 

2538 >>> a = st.deferred(lambda: st.booleans() | b) 

2539 >>> b = st.deferred(lambda: st.tuples(a, a)) 

2540 >>> a.example() 

2541 True 

2542 >>> b.example() 

2543 (False, (False, ((False, True), False))) 

2544 

2545 Examples from this strategy shrink as they normally would from the strategy 

2546 returned by the definition. 

2547 """ 

2548 return DeferredStrategy(definition) 

2549 

2550 

2551def domains() -> SearchStrategy[str]: 

2552 import hypothesis.provisional 

2553 

2554 return hypothesis.provisional.domains() 

2555 

2556 

2557@defines_strategy(force_reusable_values=True) 

2558def emails( 

2559 *, domains: SearchStrategy[str] = LazyStrategy(domains, (), {}) 

2560) -> SearchStrategy[str]: 

2561 """A strategy for generating email addresses as unicode strings. The 

2562 address format is specified in :rfc:`5322#section-3.4.1`. Values shrink 

2563 towards shorter local-parts and host domains. 

2564 

2565 If ``domains`` is given then it must be a strategy that generates domain 

2566 names for the emails, defaulting to :func:`~hypothesis.provisional.domains`. 

2567 

2568 This strategy is useful for generating "user data" for tests, as 

2569 mishandling of email addresses is a common source of bugs. 

2570 """ 

2571 local_chars = string.ascii_letters + string.digits + "!#$%&'*+-/=^_`{|}~" 

2572 local_part = text(local_chars, min_size=1, max_size=64) 

2573 # TODO: include dot-atoms, quoted strings, escaped chars, etc in local part 

2574 return builds("{}@{}".format, local_part, domains).filter( 

2575 lambda addr: len(addr) <= 254 

2576 ) 

2577 

2578 

2579def _functions(*, like, returns, pure): 

2580 # Wrapped up to use ParamSpec below 

2581 check_type(bool, pure, "pure") 

2582 if not callable(like): 

2583 raise InvalidArgument( 

2584 "The first argument to functions() must be a callable to imitate, " 

2585 f"but got non-callable like={nicerepr(like)!r}" 

2586 ) 

2587 if returns in (None, ...): 

2588 # Passing `None` has never been *documented* as working, but it still 

2589 # did from May 2020 to Jan 2022 so we'll avoid breaking it without cause. 

2590 hints = get_type_hints(like) 

2591 returns = from_type(hints.get("return", type(None))) 

2592 check_strategy(returns, "returns") 

2593 return FunctionStrategy(like, returns, pure) 

2594 

2595 

2596if typing.TYPE_CHECKING or ParamSpec is not None: 

2597 

2598 @overload 

2599 def functions( 

2600 *, pure: bool = ... 

2601 ) -> SearchStrategy[Callable[[], None]]: # pragma: no cover 

2602 ... 

2603 

2604 @overload 

2605 def functions( 

2606 *, 

2607 like: Callable[P, T], 

2608 pure: bool = ..., 

2609 ) -> SearchStrategy[Callable[P, T]]: # pragma: no cover 

2610 ... 

2611 

2612 @overload 

2613 def functions( 

2614 *, 

2615 returns: SearchStrategy[T], 

2616 pure: bool = ..., 

2617 ) -> SearchStrategy[Callable[[], T]]: # pragma: no cover 

2618 ... 

2619 

2620 @overload 

2621 def functions( 

2622 *, 

2623 like: Callable[P, Any], 

2624 returns: SearchStrategy[T], 

2625 pure: bool = ..., 

2626 ) -> SearchStrategy[Callable[P, T]]: # pragma: no cover 

2627 ... 

2628 

2629 @defines_strategy() 

2630 def functions(*, like=lambda: None, returns=..., pure=False): 

2631 # We shouldn't need overloads here, but mypy disallows default args for 

2632 # generics: https://github.com/python/mypy/issues/3737 

2633 """functions(*, like=lambda: None, returns=..., pure=False) 

2634 

2635 A strategy for functions, which can be used in callbacks. 

2636 

2637 The generated functions will mimic the interface of ``like``, which must 

2638 be a callable (including a class, method, or function). The return value 

2639 for the function is drawn from the ``returns`` argument, which must be a 

2640 strategy. If ``returns`` is not passed, we attempt to infer a strategy 

2641 from the return-type annotation if present, falling back to :func:`~none`. 

2642 

2643 If ``pure=True``, all arguments passed to the generated function must be 

2644 hashable, and if passed identical arguments the original return value will 

2645 be returned again - *not* regenerated, so beware mutable values. 

2646 

2647 If ``pure=False``, generated functions do not validate their arguments, and 

2648 may return a different value if called again with the same arguments. 

2649 

2650 Generated functions can only be called within the scope of the ``@given`` 

2651 which created them. 

2652 """ 

2653 return _functions(like=like, returns=returns, pure=pure) 

2654 

2655else: # pragma: no cover 

2656 

2657 @defines_strategy() 

2658 def functions( 

2659 *, 

2660 like: Callable[..., Any] = lambda: None, 

2661 returns: SearchStrategy[Any] | EllipsisType = ..., 

2662 pure: bool = False, 

2663 ) -> SearchStrategy[Callable[..., Any]]: 

2664 """functions(*, like=lambda: None, returns=..., pure=False) 

2665 

2666 A strategy for functions, which can be used in callbacks. 

2667 

2668 The generated functions will mimic the interface of ``like``, which must 

2669 be a callable (including a class, method, or function). The return value 

2670 for the function is drawn from the ``returns`` argument, which must be a 

2671 strategy. If ``returns`` is not passed, we attempt to infer a strategy 

2672 from the return-type annotation if present, falling back to :func:`~none`. 

2673 

2674 If ``pure=True``, all arguments passed to the generated function must be 

2675 hashable, and if passed identical arguments the original return value will 

2676 be returned again - *not* regenerated, so beware mutable values. 

2677 

2678 If ``pure=False``, generated functions do not validate their arguments, and 

2679 may return a different value if called again with the same arguments. 

2680 

2681 Generated functions can only be called within the scope of the ``@given`` 

2682 which created them. 

2683 """ 

2684 return _functions(like=like, returns=returns, pure=pure) 

2685 

2686 

2687@composite 

2688def slices(draw: Any, size: int) -> slice: 

2689 """Generates slices that will select indices up to the supplied size 

2690 

2691 Generated slices will have start and stop indices that range from -size to size - 1 

2692 and will step in the appropriate direction. Slices should only produce an empty selection 

2693 if the start and end are the same. 

2694 

2695 Examples from this strategy shrink toward 0 and smaller values 

2696 """ 

2697 check_valid_size(size, "size") 

2698 if size == 0: 

2699 step = draw(none() | integers().filter(bool)) 

2700 return slice(None, None, step) 

2701 # For slices start is inclusive and stop is exclusive 

2702 start = draw(integers(0, size - 1) | none()) 

2703 stop = draw(integers(0, size) | none()) 

2704 

2705 # Limit step size to be reasonable 

2706 if start is None and stop is None: 

2707 max_step = size 

2708 elif start is None: 

2709 max_step = stop 

2710 elif stop is None: 

2711 max_step = start 

2712 else: 

2713 max_step = abs(start - stop) 

2714 

2715 step = draw(integers(1, max_step or 1)) 

2716 

2717 if (draw(booleans()) and start == stop) or (stop or 0) < (start or 0): 

2718 step *= -1 

2719 

2720 if draw(booleans()) and start is not None: 

2721 start -= size 

2722 if draw(booleans()) and stop is not None: 

2723 stop -= size 

2724 if (not draw(booleans())) and step == 1: 

2725 step = None 

2726 

2727 return slice(start, stop, step)