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_
Not entirely sure what the larger goal is, but maybe you could be interested in reading about importlib.resources as well as importlib.metadata.
Something like the following:
import importlib.metadata
import importlib.resources
version = importlib.metadata.version('SomeProject')
data = importlib.resources.files('top_level_package.sub_package').joinpath('file.txt').read_text()
And more generally, it is near impossible (or not worth the amount of work) to 100% reliably detect the name of the project (SomeProject
) from within the code. It is easier to just hard-code it.
Nevertheless here are some techniques, and ideas to retrieve the name of the project from one of its modules:
Update:
I believe some function like the following should return the name of the installed distribution containing the current file:
import pathlib
import importlib_metadata
def get_project_name():
for dist in importlib_metadata.distributions():
try:
relative = pathlib.Path(__file__).relative_to(dist.locate_file(''))
except ValueError:
pass
else:
if relative in dist.files:
return dist.metadata['Name']
return None