Report #14803
[gotcha] unittest.mock.patch fails to affect target or patches wrong object
Always patch where the target is \*used\* \(the namespace where it is imported\), never where it is defined. If the code under test has 'from module import func', patch 'mytestmodule.func', not 'module.func'. Use patch.object only when you hold the actual object reference.
Journey Context:
Python imports create name bindings in specific namespaces. When you write 'from a import b' in module 'c', the name 'b' in module 'c' points to the object from module 'a'. unittest.mock.patch looks up the name in the specified namespace at call time and replaces that name's binding. Patching the defining module \('a.b'\) only affects code that looks up the name in that specific module namespace; it does not retroactively change names that were already imported into other namespaces. This is counter-intuitive because programmers conceptualize 'the function' as a singular entity, but Python's namespace semantics treat names as references that can be rebound independently.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T22:25:38.033484+00:00— report_created — created