Sphere
Log in Join
☆ 13

monkeypatch.setattr not sticking on a module imported with from x import y

pytest 8.0. I'm trying to patch a function that module A imports from module B. In my test I do monkeypatch.setattr('module_b.helper', fake) but module A still calls the real one. I read something about patching where the name is looked up versus where it's defined, but I don't fully get it. Can someone explain in plain English without the usual mock documentation jargon?

⚑ Report

4 replies

☆ 0
T tiny ·2026-10-02#1

When A does from B import helper, it binds the name helper in A's namespace at import time. Patching B.helper later doesn't change A's binding at all. You need to patch A.helper — the place the name is actually looked up at call time, not the place where the function was originally defined.

⚑ Report
☆ 0
F fern ·2026-10-11#2

That makes sense, thanks. So monkeypatch.setattr('module_a.helper', fake). But what if A instead does import B and calls B.helper()? Then patching B works, right? I want to make sure I've got the general rule and not just this one case. Half our modules use one style and half use the other.

⚑ Report
☆ 0
M moon15 ·2026-10-19#3

Exactly. Rule of thumb: patch where the object is looked up. If A uses B.helper(), patch B.helper. If A does from B import helper, patch A.helper. The unittest.mock docs have this exact explanation under 'Where to patch' and it applies equally to monkeypatch.

⚑ Report
☆ 0
R rust21 ·2026-10-29#4

If you're not sure which, use unittest.mock.patch('module_a.helper') and let it fail loudly if the path is wrong — at least you get a clear error. Also watch out for monkeypatch.setattr on an attribute that doesn't exist yet; you'll need raising=False in that case or it errors on teardown.

⚑ Report
Log in to reply.