title: Pytest: Patch a global variable
body: <p>How do you patch a variable with mock or pytest-mock.  Assume the variable is defined in another python script and is used by many other scripts.  I would like to mock it within <code>pytest_cmdline_main</code> so that all the scripts using that variable will be mocked accordingly.</p>
  <p>A quick example will be</p>
  <h1>in env.py</h1>
  <pre><code>VAR = &quot;something&quot;
  </code></pre>
  <h1>in conftest.py</h1>
  <pre><code>import os
  import sys
  from unittest.mock import patch
  
  
  TEST_DIR = os.path.dirname(os.path.realpath(__file__))
  
  
  class MockThings():
      def __init__(self):
          self.setup()
  
      def setup(self):
          mock_var = patch('env.VAR').start()
          mock_var.return_value = &quot;updated&quot;
  
  
  def pytest_cmdline_main(config):
      sys.path.append(TEST_DIR)
      MockThings()
  </code></pre>
  <h1>in test_something.py</h1>
  <pre><code>from env import VAR
  
  
  def test_sample():
      print(VAR)
      # do something else here
      assert False
      
  def test_sample2():
      print(VAR)
      # do something else here
      assert False
  </code></pre>
  <p>When you run <code>pytest -v</code></p>
  <p>The test will fail as expected, but under the stdout it will state something like: <code>&lt;MagicMock name='VAR' id='140102687826416'&gt;</code></p>
  <p>Because it is treating the mock as a function, if I replace the <code>print(VAR)</code> with <code>print(VAR())</code> then the print out will be correct (<code>updated</code>).</p>
  <p>How do I mock this variable, and not treat it as a function?  I know you can just set <code>VAR=&quot;updated&quot;</code> in the test function itself, but I just want it mocked and I guess this is not a great representation of my actual use case, but I just wanted to have a quick simple test code you can run and understand easily.</p>