Mock patching from/import statement in Python

patch works by patching names. You can't achieve anything by patching the name collections.defaultdict if you are using the name defaultdict (in the local namespace) to access the object. See the documentation at https://docs.python.org/3/library/unittest.mock.html#where-to-patch


If you're patching something in the same module, you can use __main__:

from mock import patch
from collections import defaultdict

with patch('__main__.defaultdict'):
    d = defaultdict()
    print 'd:', d

If you're mocking something for an imported module, however, you'll want to use that module's name so the correct reference (or name) is patched:

# foo.py

from collections import defaultdict

def bar():
    return defaultdict()


# foo_test.py    

from mock import patch
from foo import bar

with patch('foo.defaultdict'):
    print bar()

The point here is that patch wants the full path to the thing it is patching. This just looks a little weird when patching something in the current module, since folks don't often use __main__ (or have to refer to the current module, for that matter).