title: Python command line import of environment variable required before module import
body: <p>I use a module that has a default location to save files: </p>
  
  <pre><code>import foo # default directory is used to save files 
  </code></pre>
  
  <p>The module allows the use of an <em>environment variable</em> to change this location:</p>
  
  <pre><code>import os
  os.environ['foo_path'] = "my/dir/path"
  import foo # files now save in my/dir/path
  </code></pre>
  
  <p>If I import the module first, however, changing the environment variable does not help:</p>
  
  <pre><code>import os
  import foo
  os.environ['foo_path'] = "my/dir/path" #No effect, files saved in default location
  </code></pre>
  
  <p><strong>My problem is the following</strong>: 
  I want to be able to run my module via command line, and I want to allow the user to pass a path to set <code>os.environ['foo_path']</code>. </p>
  
  <p>I am using the <code>click</code> module to pass some arguments, and thought about using it to get the path from the command line. Ignoring the other arguments, this looks like this:</p>
  
  <pre><code>import click
  import os
  
  @click.command()
  @click.option('--foo_path', default=None, help='dirpath to use instead of default', type=str)
  def import_foo(foo_path):
      if foo_path:
          os.environ['foo_path'] = "my/dir/path" #Correctly changes the dirpath 
      import foo
  </code></pre>
  
  <p>This <em>works</em>, though the import in a function is a bit annoying. </p>
  
  <p>However, if <code>foo</code> is somehow imported before, the approach does not work. Imagine I need to import another module <code>bar</code> that also imports <code>foo</code>:</p>
  
  <pre><code>import click
  import bar # which imports foo
  import os
  
  @click.command()
  @click.option('--foo_path', default=None, help='dirpath to use instead of default', type=str)
  def import_foo(foo_path):
      if foo_path:
          os.environ['foo_path'] = "my/dir/path" #No effect, since foo already imported   
      import foo # not executed, since foo already imported by bar
  </code></pre>
  
  <p>Does anyone have a suggestion for passing environment required in module imports? </p>