首页 > 解决方案 > booleans().example() 总是返回 True

问题描述

重现:

In [1]: from hypothesis import strategies as st

In [2]: bool_st = st.booleans()

In [3]: all(bool_st.example() for _ in range(1000))
Out[3]: True

为什么st.booleans().example()总是返回True?我的理解是,该example方法应该返回策略可以输出的示例,并且在某种程度上随机输出。

相关地,st.sampled_from(...)似乎永远不会返回迭代中的第一项:

In [1]: from hypothesis import strategies as st

In [2]: from collections import Counter

In [3]: samp_st = st.sampled_from(list(range(10)))

In [4]: examples = [samp_st.example() for _ in range(1000)]

In [5]: cnt = Counter(examples)

In [6]: cnt.most_common()
Out[6]: [(1, 512), (2, 282), (3, 119), (4, 55), (5, 22), (6, 5), (7, 4), (8, 1)]

那么这里发生了什么?

我知道example方法文档说该方法“不应该太认真”(见这里)。但这提供的解释很少,如果能更深入地了解为什么会发生这种情况会很好。

标签: pythonpython-hypothesis

解决方案


简单:该.example()方法避免显示策略中最简单的示例,因为该示例通常是微不足道的。诚然,这对 的用处不大st.booleans().example(),但这就是原因!

对于您的意见,lists(...).example()由于我们唯一性检测的限制,请继续生成空列表 - 有关详细信息,请参阅问题 1864、1982 和 PR 1961;一旦我们有一个好的方法,我们会尽快修复它。

你可以在这里找到代码.example()


推荐阅读