title: monkeypatch a function that needs to be imported in conftest
body: <p>I'm trying to use <code>pytest.monkeypatch</code> to patch a function I've defined in another file. I then need to patch a function from another that relies on this first <code>monkeypatch</code>. Here's a simple example</p>
  
  <pre><code># class_def.py
  class C:
      def __init__(self):
          # Normally, there is something that makes self.p
          # that will use a file that will exist on production
          raise FileNotFoundError
  
  def factory():
      print('in factory')
      return C()
  
  ----
  # function_def.py
  from .class_def import factory
  
  foo = factory()
  
  def bar():
      return 0
  
  ----
  # conftest.py
  from unittest.mock import MagicMock
  
  import pytest
  
  import playground.class_def
  
  @pytest.fixture(autouse=True)
  def patch_c(monkeypatch):
      fake_c = MagicMock()
      def factory():
          print('in monkey factory')
          return fake_c
      monkeypatch.setattr('playground.class_def.factory', factory)
  
  from .function_def import bar
  
  # Then I would patch bar
  </code></pre>
  
  <p>And running <code>pytest .</code> will fail with <code>FileNotFoundError</code>. I believe this happens because I am calling <code>foo = factory()</code> at the top level of <code>function_def.py</code>. I expected this not to happen because I am patching <code>factory</code> before doing this import, but that doesn't seem to be happening. Is there a way to ensure this <code>monkeypatch.setattr</code> will go into effect before <code>from .function_def import bar</code> in <code>conftest.py</code>?</p>
  
  <p>Also, the file structure looks like</p>
  
  <pre><code>playground
  |--- __init__.py
  |--- conftest.py
  |--- class_def.py
  |--- function_def
  </code></pre>