In [1]:
import tohu
from tohu import *
from collections import namedtuple
from utils import print_generated_sequence
In [2]:
print(f"Tohu version: {tohu.__version__}")
In [3]:
letters = 'abcdefghijklmnopqrstuvwxyz'
Foobar = namedtuple('Foobar', ('foo', 'bar'))
items = [Foobar(c+c, c+c+c) for c in letters]
items[:3]
Out[3]:
Let's define a generator xx
which selects random elements from items
, and two other generators yy
and zz
which extract individual attributes from these elements.
In [4]:
xx = SelectOne(items)
yy = xx.foo
zz = xx.bar
When xx
is reset, internally this also automatically resets yy
and zz
with the same seed (because they are "dependent generators" whose parent is xx
).
In [5]:
xx.reset(seed=12345)
print_generated_sequence(xx, num=10, sep='\n')
print_generated_sequence(yy, num=10)
print_generated_sequence(zz, num=10)
This also works if xx
, yy
, zz
are defined inside a CustomGenerator
.
In [6]:
class QuuxGenerator(CustomGenerator):
xx = SelectOne(items)
yy = xx.foo
zz = xx.bar
ww = yy # alias
In [7]:
g = QuuxGenerator()
In [8]:
list(g.generate(10, seed=12345))
Out[8]:
Just for illustration, let's repeat the last example but with a different set of items (produced by another custom generator, although this doesn't really matter).
In [9]:
class FoobarGenerator(CustomGenerator):
foo = Integer(0, 100)
bar = HashDigest(length=8)
In [10]:
fg = FoobarGenerator()
In [11]:
items2 = list(fg.generate(10, seed=12345))
items2
Out[11]:
In [12]:
class QuuxGenerator(CustomGenerator):
xx = SelectOne(items2)
yy = xx.foo
zz = xx.bar
In [13]:
g = QuuxGenerator()
In [14]:
g.reset(seed=99999); print_generated_sequence(g, num=10, sep='\n')
In [15]:
class QuuxGenerator(CustomGenerator):
aaa = Integer(0, 100)
bbb = HashDigest(length=6)
In [16]:
g = QuuxGenerator()
Using ExtractAttribute
we can produce \"derived\" generators which extract the attributes aaa
, bbb
from the elements produced by g
.
In [17]:
h1 = ExtractAttribute(g, 'aaa')
h2 = ExtractAttribute(g, 'bbb')
In [18]:
g.reset(seed=99999)
print_generated_sequence(g, num=10, sep='\n')
print_generated_sequence(h1, num=10)
print_generated_sequence(h2, num=10)
Create mapping from lowercase to uppercase letters.
In [19]:
letters = 'abcdefghijklmnopqrstuvwxyz'
mapping = dict([(c, c.upper()) for c in letters])
Create generator g
which selects a random letter and generator h
which looks up each letter in the lowercase->uppercase mapping.
In [20]:
g = SelectOne(letters)
h = Lookup(g, mapping)
In [21]:
g.reset(seed=12345)
print_generated_sequence(g, num=20)
print_generated_sequence(h, num=20)
In [ ]: