Python Hypothesis Custom Strategies with Pytest
Learn to define custom Hypothesis strategies for property-based testing and use them with pytest, covering @composite, .map, and .filter.

When built-in Hypothesis strategies cannot express the constraints in your domain, you can define a custom strategy with @composite and pass it to @given in pytest. This lets every generated example satisfy your invariants by construction, so tests focus on behavior rather than on filtering bad data.
Why Custom Strategies Matter
Hypothesis provides built-in strategies for integers, strings, lists, dictionaries, and more. These work well for generic inputs, but they often do not match the shape of real data. For example, a function that processes user records may need a username with a minimum length, an email address matching a normal email format, and an age between 18 and 120. You can use .filter on built-in strategies, but heavy filtering can reject many examples and make shrinking less effective. A custom strategy generates only valid values from the start, keeping the search focused and failures reproducible.
Composing Strategies with .map and .filter
Before reaching for @composite, consider transforming existing strategies with .map and .filter. .map applies a function to each generated value; .filter keeps only values that satisfy a predicate.
from hypothesis import strategies as st
# Generate even integers from 0 to 100
even_ints = st.integers(min_value=0, max_value=50).map(lambda n: n * 2)
# Generate non-empty strings of ASCII lowercase letters
lowercase_words = st.text(min_size=1, alphabet=st.characters(min_codepoint=97, max_codepoint=122)).map is concise and often sufficient. When you need to coordinate multiple values or enforce constraints that depend on more than one field, use @composite.
Building Complex Strategies with @composite
The @composite decorator turns a function into a strategy factory. Inside the function, draw pulls a value from another strategy, and the function returns the combined value. This lets you use normal Python control flow to build structured data.
from hypothesis import strategies as st
from hypothesis.strategies import composite
@composite
def user_strategy(draw):
username = draw(st.text(min_size=3, max_size=20, alphabet=st.characters(whitelist_categories=('Ll', 'Lu', 'Nd'))))
email = draw(st.emails())
age = draw(st.integers(min_value=18, max_value=120))
return {'username': username, 'email': email, 'age': age}A @composite function returns the generated value, not a strategy. If you are simply constructing an object from a callable and arguments, st.builds() can be a lighter alternative.
Integrating Custom Strategies with pytest
Hypothesis integrates with pytest through @given. Pass a custom strategy as an argument, and Hypothesis supplies generated values to the test function.
from hypothesis import given
@given(user_strategy())
def test_user_validation(user):
assert len(user['username']) >= 3
assert '@' in user['email']
assert 18 <= user['age'] <= 120Save the file as a test module and run pytest. Hypothesis runs each @given test with a default of 100 examples; you can adjust that with @settings(max_examples=...). If an example fails, Hypothesis attempts to produce a minimal counterexample.
You can use pytest fixtures alongside @given, but the fixture and generated arguments are independent. Keep the custom strategy at module level and call it inside @given.
Example: A Custom Strategy for a Domain Object
Suppose you have a Product class with a SKU in the format three uppercase letters, a hyphen, and four digits, plus a price that is a positive number with two decimal places.
from dataclasses import dataclass
from hypothesis import strategies as st
from hypothesis.strategies import composite
@dataclass
class Product:
sku: str
price: float
@composite
def product_strategy(draw):
sku_prefix = draw(st.text(min_size=3, max_size=3, alphabet=st.characters(min_codepoint=65, max_codepoint=90)))
sku_suffix = draw(st.integers(min_value=0, max_value=9999).map(lambda n: f'{n:04d}'))
sku = sku_prefix + '-' + sku_suffix
price = draw(st.floats(min_value=0.01, max_value=1000.00, allow_nan=False, allow_infinity=False).map(lambda x: round(x, 2)))
return Product(sku=sku, price=price)Then use it in a property-based test:
@given(product_strategy())
def test_product_total(product):
assert product.price > 0
assert product.sku[3] == '-'This strategy generates only valid products. If a test fails, Hypothesis shrinks the product to a simpler failing example, making the failure easier to debug.
Performance and Shrinking Considerations
Custom strategies affect both generation and shrinking. @composite draws each component separately, which adds some overhead compared to a single built-in strategy. The overhead is usually small, but it can matter if you generate huge numbers of examples.
Shrinking matters more. Hypothesis simplifies each drawn component while trying to find the smallest failing example. If you start from a broad strategy and use a strict .filter, the shrinker can spend extra effort finding values that still pass the predicate. Prefer generating valid values directly, as in the SKU example, over filtering broad strings. Also avoid .map transformations that destroy too much information; simpler transformations usually shrink more intuitively.
When to Write a Custom Strategy vs. Using Built-ins
Write a custom strategy when the built-in strategies cannot express your constraints, when filtering rejects too many examples, or when you want to reuse the same generation logic across tests. Prefer .map or .filter when a small transformation on an existing strategy is enough. For coordinated constraints across multiple fields, @composite is the right tool.
A custom strategy also gives you one place to update when domain rules change. Instead of editing every property test that constructs an object, you modify the strategy and all tests that use it pick up the new rules automatically.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.