title: How to access symbols in __init__.py from __main__.py?
body: <p>I have a module - let's call it <code>foo</code> - and I want to make it usable via a <code>python -m foo</code> call. My program look like this:</p>
  
  <pre><code>my_project
  ├──  foo
  │   └── __init__.py
  └── my_program.py
  </code></pre>
  
  <p>In <code>__init__.py</code> I have some code which I run when calling <code>python -m foo</code>:</p>
  
  <pre><code>def bar(name):
      print(name)
  
  # -- code used to 'run' the module
  def main(name):
      bar("fritz")
  
  if __name__ == "__main__":
      main()
  </code></pre>
  
  <p>Since I have a fair amount of execution code in <code>__init__.py</code> now (<code>argparse</code> stuff and some logic) I want to separate it into a <code>__main__.py</code>:</p>
  
  <pre><code>my_project
  ├──  foo
  │   ├── __init__.py
  │   └── __main__.py
  └── my_program.py
  </code></pre>
  
  <p>Despite that looks very simple to me I didn't manage to import stuff located in <code>__init__.py</code> from <code>__main__.py</code> yet.</p>
  
  <p>I know - if <code>foo</code> is located in <code>site-packages</code> or accessible via <code>PYTHONPATH</code> I can just <code>import foo</code>..</p>
  
  <p>But in case I want to <strong>execute</strong> <code>__main__.py</code> <strong>directly</strong> (e.g. from some IDE) with <code>foo</code> located <em>anywhere</em> (i.e. not a folder where Python looks for packages) - is there a way to import <code>foo</code> (<code>__init__.py</code> from the same directory)?</p>
  
  <p>I tried <code>import .</code> and <code>import foo</code> - but both approaches fail (because they just mean something else of course)</p>
  
  <p>What I <em>can</em> do - at least to explain my goal - is something like this:</p>
  
  <pre><code>sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
  import foo
  </code></pre>
  
  <p>Works, but is ugly and a bit dangerous since I don't even know if I really import <code>foo</code> from the same directory..</p>