title: Why does PYTHONPATH with trailing colon add current directory to sys.path?
body: <p>Consider a Python project like this:</p>
  
  <pre><code>foo/
      __init__.py
  scripts/
      run.py
  demo.sh
  </code></pre>
  
  <p>Under normal circumstances, attempting to import from the <code>foo</code> package will
  fail if you run the script from the root of the project, because default Python
  behavior is to add the <em>directory of script invoking the Python interpreter</em>
  (and not necessarily the current directory) to <code>sys.path</code>.
  (<a href="https://docs.python.org/2/library/sys.html#sys.path" rel="noreferrer">docs</a>):</p>
  
  <pre><code>python scripts/run.py
  </code></pre>
  
  <p>However, I recently noticed that such imports were working on my box, and I
  tracked it down to some surprising behavior related to PYTHONPATH. In my Bash
  profile I had added a directory to PYTHONPATH:</p>
  
  <pre><code>export PYTHONPATH="/some/path:$PYTHONPATH"
  </code></pre>
  
  <p>If PYTHONPATH is initially empty, that (somewhat sloppy, but commonly seen)
  form of the command will leave a trailing colon:</p>
  
  <pre><code>echo $PYTHONPATH
  /some/path:
  </code></pre>
  
  <p>I had always assumed that this trailing punctuation had no impact, but it
  appears that the trailing colon was the cause of the mysteriously successful
  import. Leading or trailing colons (or even a defined but empty PYTHONPATH)
  will result in <code>sys.path</code> containing an empty string <strong>before</strong> the <code>site</code>
  module loads, which in turn leads to the current working directory being added
  to <code>sys.path</code>.</p>
  
  <p>Here are a Python script and a Bash script to demonstrate. I got the same
  behavior using both Python 2.7 and Python 3.3.</p>
  
  <p>Python script: <code>run.py</code>:</p>
  
  <pre><code>import sys, os
  
  pp = os.environ.get('PYTHONPATH')
  
  try:
      import foo
      print 'OK'
      assert os.getcwd() in sys.path
      assert pp == '' or pp.startswith(':') or pp.endswith(':')
  
  except Exception:
      print 'FAIL'
      assert os.getcwd() not in sys.path
      assert pp is None
  </code></pre>
  
  <p>Bash script: <code>demo.sh</code>:</p>
  
  <pre><code># Import fails.
  unset PYTHONPATH;  python scripts/run.py
  
  # Import succeeds -- to my surprise.
  PYTHONPATH=''      python scripts/run.py
  PYTHONPATH='/tmp:' python scripts/run.py
  PYTHONPATH=':/tmp' python scripts/run.py
  </code></pre>
  
  <p><strong>My questions</strong>:</p>
  
  <ul>
  <li><p>Am I understanding the situation correctly, or have I somehow gone astray?</p></li>
  <li><p>Is this documented anywhere? I did not find anything. At a minimum, I am
  posting this information here in case it will help others.</p></li>
  <li><p>Am I alone in finding this behavior unexpected?</p></li>
  </ul>