title: Pytest Monkeypatch Doesn't Apply To Imported Function
body: <p>I have a module set up roughly as follows:</p>
  <pre class="lang-py prettyprint-override"><code># foo.py
  def generate_things_based_on_other_things():
    # some nasty things here
  
  # bar.py
  from foo import generate_things_based_on_other_things as generate
  
  def coo():
    generate()
  
  # conftest.py
  import pytest
  
  @pytest.fixture(autouse=True)
  def patch_generate(monkeypatch):
    def mock_generate():
      print(&quot;hello!&quot;)
  
    monkeypatch.setattr(&quot;app.bar.generate&quot;, mock_generate)
  
  # test_bar.py
  from bar import coo
  
  def test_coo():
    coo()
  </code></pre>
  <p>As per <a href="https://stackoverflow.com/questions/31306080/pytest-monkeypatch-isnt-working-on-imported-function">this answer</a> I made sure to monkeypatch the actual imported instance of the function. Any other path throws a <code>&quot;does not exist on module&quot;</code> error.
  However when I run the test I hit an error, because the original function <code>generate</code> is being called, despite it being monkeypatched.
  I can't figure out why this patch won't stick the way I expect it too.
  I would expect this test to print &quot;hello!&quot;.</p>