How do I get the current topmost package, i.e., the name defined in setup.py?
Here is my tree:
. |-- README.md |-- the_project_name_for_this_pkg | |-- __init__.py | |-- __main__.py | |-- _config | | `-- foo.conf | |-- _data | | `-- logging.yml | `-- tests | |-- __init__.py | `-- test_foo.py <--- # executing from here |-- requirements.txt `-- setup.py 4 directories, 9 files The only solution I've gotten to work so far is this:
import os import sys os.path.basename(sys.path[1]) But this is obviously a bad solution. Other solutions like having a __name__ in my uppermost __init__.py file and using ast.parse to read in the relevant section of setup.py also seems cumbersome.
Other solutions I've tried—by calling them within a unittest.TestCase inheriting class in my tests python [sub]package—include checking sys.modules[__name__], inspect.getmodule & inspect.stack, as well as the answers to these questions:
- Python - Get path of root project structure
- Get full package module name
- Get fully qualified class name of an object in Python
- How can I access the current executing module or class name in Python?
- Get full caller name (package.module.function) (Python recipe)
- https://docs.python.org/2/library/modulefinder.html
BTW: In case you were wondering why I want the package name… it's so I can run things like:
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')
test_foo.pyit should already be defined within the package itself, just use the package name directly there.inspect, orsys.modules.setup.py; the package system is bolted onto Python after the fact, and given that string for the package name don't typically change, it's a lot less hassle to just hardcode that samestrvalue intotest_foo.pythat rather than trying to come up with ways to resolve that in Python.setup.pythat would have values that reference the module that has the resources you need. From your code (or any other package, fro that matter) simply query for that, and use that result to feed intoresource_filenameto get what is needed.