Mehdi
Mehdi

Reputation: 775

Get package name of caller script from imported python file

I have a project that will be zipped and run from Spark, let's call it "client" project.

I would like, on a library imported by a script within this client project, to read some static config file the "client" program will provide following a certain structure.

However, I can't seem to find a way to get the package name of the script importing the library's file, in order to read the configuration file.

Note: I use pkg_resources as the project will be packaged as a Zip file and will therefore lack the access to the file structure of the project.


So, for a client project with the current structure:

project/
├── package1/
│   ├── __init__.py
│   ├── main.py
│   └── conf/
│       └── conf.txt

main.py:

from library import SuperClass

class Main(SuperClass):
    
    def __init__(self):
        super().__init__()
        print(self.conf) # conf.txt file read from SuperClass 

And on the library's side: library.py

import importlib.resources as pkg_resources

class SuperClass:
    
    def __init__(self):
        self.conf = self.__read_conf()

    def __read_conf(self):
        return pkg_resources.read_text('????conf', 'conf.txt') # issue here

So my question is: what would be the value of the first argument of pkg_resources.read_text?

Upvotes: 1

Views: 221

Answers (1)

Sam Newbold
Sam Newbold

Reputation: 11

Python has deprecated pkg_resources in favor of importlib.resources: https://docs.python.org/3/library/importlib.resources.html. The importlib.resources.files() function takes an anchor argument which should be the package name, but if it is omitted the current package us used, which is what you are desiring.

Upvotes: 0

Related Questions