title: How do I get the current 'package' name? (setup.py)
body: <p>How do I get the current topmost package, i.e., the name defined in setup.py?</p>
  
  <p>Here is my <code>tree</code>:</p>
  
  <pre><code>.
  |-- README.md
  |-- the_project_name_for_this_pkg
  |   |-- __init__.py
  |   |-- __main__.py
  |   |-- _config
  |   |   `-- foo.conf
  |   |-- _data
  |   |   `-- logging.yml
  |   `-- tests
  |       |-- __init__.py
  |       `-- test_foo.py   &lt;--- # executing from here
  |-- requirements.txt
  `-- setup.py
  
  4 directories, 9 files
  </code></pre>
  
  <p>The only solution I've gotten to work so far is this:</p>
  
  <pre><code>import os
  import sys
  
  
  os.path.basename(sys.path[1])
  </code></pre>
  
  <p>But this is obviously a bad solution. Other solutions like having a <code>__name__</code> in my uppermost <code>__init__.py</code> file and using <a href="https://docs.python.org/3/library/ast.html#ast.parse" rel="noreferrer"><code>ast.parse</code></a> to read in the relevant section of <code>setup.py</code> also seems cumbersome.</p>
  
  <p>Other solutions I've tried—by calling them within a <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase" rel="noreferrer"><code>unittest.TestCase</code></a> inheriting <code>class</code> in my <code>tests</code> python [sub]package—include checking <code>sys.modules[__name__]</code>, <a href="https://docs.python.org/3/library/inspect.html#inspect.getmodule" rel="noreferrer"><code>inspect.getmodule</code></a> &amp; <a href="https://docs.python.org/3/library/inspect.html#inspect.stack" rel="noreferrer"><code>inspect.stack</code></a>, as well as the answers to these questions:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/q/25389095">Python - Get path of root project structure</a></li>
  <li><a href="https://stackoverflow.com/q/11705055">Get full package module name</a></li>
  <li><a href="https://stackoverflow.com/q/2020014">Get fully qualified class name of an object in Python</a></li>
  <li><a href="https://stackoverflow.com/q/602846">How can I access the current executing module or class name in Python?</a></li>
  <li><a href="http://code.activestate.com/recipes/578352-get-full-caller-name-packagemodulefunction/" rel="noreferrer">Get full caller name (package.module.function) (Python recipe)</a></li>
  <li><a href="https://docs.python.org/2/library/modulefinder.html" rel="noreferrer">https://docs.python.org/2/library/modulefinder.html</a></li>
  </ul>
  
  <p>BTW: In case you were wondering why I want the package name… it's so I can run things like:</p>
  
  <pre><code>import pkg_resources
  
  
  version   = pkg_resources.require('the_project_name_for_this_pkg')[0].version
  data_file = path.join(resource_filename('the_project_name_for_this_pkg', '__init__.py'),
                        '_config', 'data_file.txt')
  </code></pre>