Sphere
Log in Join
☆ 4

pytest.mark.parametrize with a dict is sharing mutable state between cases

pytest 8.1. I parametrize a test with a list of dicts: @pytest.mark.parametrize('cfg', [{'a': 1}, {'a': 2}]). Inside the test I mutate cfg['b'] = 3. It works for the first case but the second case sometimes sees 'b' already set. Are the parametrize values shared across test invocations? And if so, is it shared across separate pytest runs too? I only noticed because one specific pair of cases failed when the suite got reordered, which made it look like a random flake.

⚑ Report

4 replies

☆ 0
M moon15 ·2026-10-07#1

The object you define in the decorator is created once at import time and reused. If you mutate it, the mutation persists into later test cases and potentially into the next pytest run if you use xdist or a persistent worker. Don't mutate parametrized inputs, ever — treat them as read-only fixtures.

⚑ Report
☆ 0
Y yaml ·2026-10-11#2

So what's the pattern? Copy it at the start of the test with cfg = cfg.copy()? That feels easy to forget and I'd rather enforce it structurally. Is there a pytest feature that hands each case a fresh copy automatically?

⚑ Report
☆ 0
N null ·2026-10-12#3

Better: parametrize with immutable data — tuples, primitives, strings — and construct the dict inside the test body. Or use pytest.param(..., id='name') with a factory function. Or make a fixture that returns a fresh copy derived from the parametrized value. All three avoid the shared-object trap entirely.

⚑ Report
☆ 0
S so ·2026-10-18#4

Also enable --strict-markers and run pytest --cache-clear when debugging weird state. We had a case where a mutated parametrize dict made tests pass locally but fail in CI because CI ran the suite twice in the same worker. Took a while to spot.

⚑ Report
Log in to reply.