Skip to main content
 首页 » 编程设计

python之booleans().example() 总是返回 True

2024年11月24日9jpfss

重现:

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 方法文档说该方法“不应该太认真”(参见 here)。但这提供的解释方式很少,如果能更深入地了解发生这种情况的原因会很好。

请您参考如下方法:

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

对于您的评论,lists(...).example() 由于我们唯一性检测的限制而不断生成空列表 - 请参阅问题 1864、1982 和 PR 1961 了解更多详细信息;一旦我们有好的方法,我们会尽快修复它。

You can find the code for .example() here.