How to generate functions

31 views
Skip to first unread message

Donald Trump

unread,
Jan 4, 2023, 9:17:40 AM1/4/23
to hypothes...@googlegroups.com
Hey there,

I read the documentation but I don't understand how Hypothesis can generate functions for me. Here is a screenshot of what I tried. I tried printing it out. print(fun(price)) is always None (I hid those in the screenshot).

I want Hypothesis to create random Callable methods that map one or two integers to a single integer. Could be like

* (x, y) -> 2 + 2*x - y
* (x, y) -> 2 + 3*y

What did I do wrong and how can I make it better?

image.png

Jens Troeger

unread,
Jan 9, 2023, 5:50:01 PM1/9/23
to Hypothesis users
It sounds like you’re looking for “grammar-based fuzzing”, so perhaps take a look at Hypothesis issue #170.

If you just need simple mathematical expressions then maybe the from_regex() strategy might be useful:

@given(
    expr=st.from_regex(r"^[0-9] [+-] [0-9] \* [xy] [+-] [xy]$"),
    x=st.integers(min_value=0, max_value=20),
    y=st.integers(min_value=0, max_value=20),
)
def bla(expr, x, y):
    print(eval(expr))

You can get endlessly creative with your regex here.

Bryan Hauss

unread,
Jan 11, 2023, 2:19:26 AM1/11/23
to Hypothesis users
Amazing, it works.

Is there any way to transform expr to a Callable[float], float] ? For the instance I am creating in the test, I need a Callable that maps a float to a float.

Jens Troeger

unread,
Jan 11, 2023, 3:30:17 PM1/11/23
to Hypothesis users
Hmm… does this help:

>>> f = eval("lambda x: x*x")
>>> f
<function <lambda> at 0x1101e6430>
>>> f(2)
4

For typing take a look here
Reply all
Reply to author
Forward
0 new messages