title: Python: How to mock class attribute initializer function
body: <p>I would like to mock a module-level function used to initialize a class-level (not instance) attribute.  Here's a simplified example:</p>
  
  <pre><code># a.py    
  def fn(): 
      return 'asdf'
  
  class C:
      cls_var = fn()
  </code></pre>
  
  <p>Here's a unittest attempting to mock a.fn():</p>
  
  <pre><code># test_a.py 
  import unittest, mock
  import a
  
  class TestStuff(unittest.TestCase):
      # we want to mock a.fn so that the class variable
      # C.cls_var gets assigned the output of our mock
  
      @mock.patch('a.fn', return_value='1234')
      def test_mock_fn(self, mocked_fn):
          print mocked_fn(), " -- as expected, prints '1234'"
          self.assertEqual('1234', a.C.cls_var) # fails! C.cls_var is 'asdf'
  </code></pre>
  
  <p>I believe the problem is <a href="https://docs.python.org/3.6/library/unittest.mock.html#where-to-patch" rel="nofollow">where to patch</a> but I've tried both variations on import with no luck.  I've even tried moving the import statement into test_mock_fn() so that the mocked a.fn() would "exist" before a.C comes into scope - nope, still fails.</p>
  
  <p>Any insight would be greatly appreciated!</p>