title: How to share global variables between tests?
body: <p>I have a global variable in conftest.py and use it in tests. For example:</p>
  
  <p><em>conftest.py</em></p>
  
  <pre><code>api_version = 'v25'
  api_url = 'http://www.foobar.com/' + api_version
  </code></pre>
  
  <p><em>test_foo.py</em></p>
  
  <pre><code>from conftest import api_url
  import requests
  
  @pytest.fixture
  def data():
      return requests.request("GET", api_url)
  
  test_bar(data):
      assert data is not None
  </code></pre>
  
  <hr>
  
  <p>Now I want to be able to change api_version from cmd for testing other api version. So I modified conftest.py in the following way:</p>
  
  <p><em>conftest.py</em></p>
  
  <pre><code>api_url = None
  
  def pytest_addoption(parser):
      parser.addoption("--api_version", action="store", default="v25", help="By default: v25")
  
  @pytest.fixture(autouse=True, scope='session')
  def cmd_param(pytestconfig):
      api_version = pytestconfig.getoption("--mobile_api_ver").lower()
      global api_url
      if api_version in ['v24', 'v25', 'v26', 'v27']:
          api_url = 'http://www.foobar.com/' + api_version
      else:
          raise ValueError('Unknown api version: ' + api_version)
  </code></pre>
  
  <p>But this doesn't work as I expected because all imports execute before fixtures and test_foo import <em>api_url = None</em> <strong>before</strong> cmd_param fixture redefines this.
  Then i write get_api_url method and call it from test module:</p>
  
  <p><em>conftest.py</em></p>
  
  <pre><code>api_url = None
  
  def pytest_addoption(parser):
      parser.addoption("--api_version", action="store", default="v25", help="By default: v25")
  
  @pytest.fixture(autouse=True, scope='session')
  def cmd_param(pytestconfig):
      api_version = pytestconfig.getoption("--mobile_api_ver").lower()
      global api_url
      if api_version in ['v24', 'v25', 'v26', 'v27']:
          api_url = 'http://www.foobar.com/' + api_version
      else:
          raise ValueError('Unknown api version: ' + api_version)
  
  def get_api_url():
      return api_url
  </code></pre>
  
  <p>But now I was forced to change test_foo.py too:</p>
  
  <p><em>test_foo.py</em></p>
  
  <pre><code>from conftest import get_api_url
  import requests
  
  @pytest.fixture
  def data():
  
      return requests.request("GET", get_api_url())
  
  test_bar(data):
      assert data is not None
  </code></pre>
  
  <p>It works, but solution looks awkward. Is there a more elegant way to use custom cmd options without changing test files?</p>