Debian Codegraph @

website/content/2016-08-19-recursive-data.md

raw symbols SCIP
1 ---
2 tags: technical, python, intro
3 date: 2016-08-19 10:00
4 title: Generating recursive data
5 author: drmaciver
6 ---
7
8 Sometimes you want to generate data which is *recursive*.
9 That is, in order to draw some data you may need to draw
10 some more data from the same strategy. For example we might
11 want to generate a tree structure, or arbitrary JSON.
12
13 Hypothesis has the *recursive* function in the hypothesis.strategies
14 module to make this easier to do. This is an article about how to
15 use it.
16
17 <!--more-->
18
19 Lets start with a simple example of drawing tree shaped data:
20 In our example a tree is either a single boolean value (a leaf
21 node), or a tuple of two child trees. So a tree might be e.g. True,
22 or (False, True), or ((True, True), False), etc.
23
24 First off, it might not be obvious that you *need* the recursive
25 strategy. In principle you could just do this with composite:
26
27
28 ```python
29 import hypothesis.strategies as st
30
31
32 @st.composite
33 def composite_tree(draw):
34 return draw(
35 st.one_of(
36 st.booleans(),
37 st.tuples(composite_tree(), composite_tree()),
38 )
39 )
40 ```
41
42 If you try drawing examples from this you'll probably see one of
43 three scenarios:
44
45 1. You'll get a single boolean value
46 2. You'll get a very large tree
47 3. You'll get a RecursionError from a stack overflow
48
49 It's unlikely that you'll see any non-trivial small examples.
50
51 The reason for this is that this sort of recursion tends to
52 explode in size: If this were implemneted as a naive random
53 generation process then the expected size of the tree would
54 be infinite. Hypothesis has some built in limiters to stop
55 it ever trying to actually generate infinitely large amounts
56 of data, but it will still tend to draw trees that are very
57 large if they're not trivial, and it can't do anything about
58 the recursion problem.
59
60 So instead of using this sort of unstructured recursion,
61 Hypothesis exposes a way of doing recursion in a slightly more
62 structured way that lets it control the size of the
63 generated data much more effectively. This is the recursive
64 strategy.
65
66 In order to use the recursive strategy you need two parts:
67
68 1. A base strategy for generating "simple" instances of the
69 data that you want.
70 2. A function that takes a child strategy that generates data
71 of the type you want and returns a new strategy generating
72 "larger" instances.
73
74 So for example for our trees of booleans and tuples we could
75 use booleans() for the first and something for returning tuples
76 of children for the second:
77
78 ```python
79 recursive_tree = st.recursive(
80 st.booleans(), lambda children: st.tuples(children, children)
81 )
82 ```
83
84 The way to think about the recursive strategy is that you're
85 repeatedly building up a series of strategies as follows:
86
87 ```python
88 s1 = base
89 s2 = one_of(s1, extend(s1))
90 s3 = one_of(s2, extend(s2))
91 ...
92 ```
93
94 So at each level you augment the things from the previous
95 level with your extend function. Drawing from the resulting
96 recursive strategy then picks one of this infinite sequence
97 of strategies and draws from it (this isn't quite what happens
98 in practice, but it's pretty close).
99
100 The resulting strategy does a much better job of drawing small
101 and medium sized trees than our original composite based one
102 does, and should never raise a RecursionError:
103
104 ```
105 >>> recursive_tree.example()
106 ((False, True), ((True, True), False))
107
108 >>> recursive_tree.example()
109 ((((False, False), True), False), False)
110
111 >>> recursive_tree.example()
112 (False, True)
113
114 >>> recursive_tree.example()
115 True
116
117 ```
118
119 You can also control the size of the trees it draws with the
120 third parameter to recursive:
121
122 ```
123 >>> st.recursive(st.booleans(), lambda children: st.tuples(children, children), max_leaves=2).example()
124 True
125
126 >>> st.recursive(st.booleans(), lambda children: st.tuples(children, children), max_leaves=2).example()
127 (True, False)
128 ```
129
130 The max_leaves parameter controls the number of values drawn from
131 the 'base' strategy. It defaults to 50, which will tend to give you
132 moderately sized values. This helps keep example sizes under control,
133 as otherwise it can be easy to create extend functions which cause the
134 size to grow very rapidly.
135
136 In this particular example, Hypothesis will typically not hit the default,
137 but consider something like the following:
138
139 ```
140 >>> st.recursive(st.booleans(), lambda children: st.lists(children, min_size=3)).example()
141 [[False,
142 True,
143 False,
144 False,
145 False,
146 True,
147 True,
148 True,
149 False,
150 False,
151 False,
152 True,
153 True,
154 False],
155 False,
156 [False, True, False, True, False],
157 [True, False, True, False, False, False]]
158 ```
159
160 In this case the size of the example will tend to push up against the max_leaves value
161 because extend() grows the strategy in size quite rapidly, so if you want larger
162 examples you will need to turn up max_leaves.