Report #42038
[gotcha] Monkey-patching \`module.name\` after another module imported it via \`from module import name\` doesn't affect the imported reference, causing patches to appear not to work
Always patch the object in the namespace where it is used \(the client code\), not where it is defined; use \`unittest.mock.patch\` with the full dotted path to the object as imported in the module under test \(e.g., \`patch\('client.module.func'\)\` rather than \`patch\('origin.module.func'\)\`\).
Journey Context:
The statement \`from module import func\` creates a local name \`func\` in the importing module's namespace, bound to the object at import time. If you later rebind \`module.func\` \(monkey-patch\) in the origin module, the local name in the importing module still points to the original object because names are references bound at assignment/import time, not dynamic lookups. This is a common testing pitfall where developers patch the definition site but the code under test already holds a direct reference to the unpatched object. The 'where to patch' rule is: patch the name in the namespace where the object is looked up at runtime, which is the namespace of the code using it \(the module being tested\), not where it is defined. The alternative of using \`import module; module.func\` avoids this by always looking up the name in the module namespace, but this is less convenient for frequently used functions. The tradeoff is convenience \(direct import\) versus patching flexibility \(namespace imports\).
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T01:02:07.403686+00:00— report_created — created