MCPcopy Create free account
hub / github.com/HypothesisWorks/hypothesis / ArrayStrategy

Class ArrayStrategy

hypothesis/src/hypothesis/extra/array_api.py:308–447  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

306
307
308class ArrayStrategy(st.SearchStrategy):
309 def __init__(
310 self, *, xp, api_version, elements_strategy, dtype, shape, fill, unique
311 ):
312 super().__init__()
313 self.xp = xp
314 self.elements_strategy = elements_strategy
315 self.dtype = dtype
316 self.shape = shape
317 self.fill = fill
318 self.unique = unique
319 self.array_size = math.prod(shape)
320 self.builtin = find_castable_builtin_for_dtype(xp, api_version, dtype)
321 self.finfo = None if self.builtin is not float else xp.finfo(self.dtype)
322
323 def check_set_value(self, val, val_0d, strategy):
324 if val == val and self.builtin(val_0d) != val:
325 if self.builtin is float:
326 assert self.finfo is not None # for mypy
327 try:
328 is_subnormal = 0 < abs(val) < self.finfo.smallest_normal
329 except Exception:
330 # val may be a non-float that does not support the
331 # operations __lt__ and __abs__
332 is_subnormal = False
333 if is_subnormal:
334 raise InvalidArgument(
335 f"Generated subnormal float {val} from strategy "
336 f"{strategy} resulted in {val_0d!r}, probably "
337 f"as a result of array module {self.xp.__name__} "
338 "being built with flush-to-zero compiler options. "
339 "Consider passing allow_subnormal=False."
340 )
341 raise InvalidArgument(
342 f"Generated array element {val!r} from strategy {strategy} "
343 f"cannot be represented with dtype {self.dtype}. "
344 f"Array module {self.xp.__name__} instead "
345 f"represents the element as {val_0d}. "
346 "Consider using a more precise elements strategy, "
347 "for example passing the width argument to floats()."
348 )
349
350 def do_draw(self, data):
351 if 0 in self.shape:
352 return self.xp.zeros(self.shape, dtype=self.dtype)
353
354 if self.fill.is_empty:
355 # We have no fill value (either because the user explicitly
356 # disabled it or because the default behaviour was used and our
357 # elements strategy does not produce reusable values), so we must
358 # generate a fully dense array with a freshly drawn value for each
359 # entry.
360 elems = data.draw(
361 st.lists(
362 self.elements_strategy,
363 min_size=self.array_size,
364 max_size=self.array_size,
365 unique=self.unique,

Callers 2

_arraysFunction · 0.70

Calls

no outgoing calls

Tested by 1