0

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?

Mehdi
  • 591
  • 7
  • 16
  • 1
    Couldn't you pass the configuration filepath to the class and supercall __init__ method, save it in a class variable and use it? – Nicolò Gasparini Nov 08 '20 at 20:55
  • You probably need to introspect the value of `self`. It probably has a full class name, containing the parent module or package name. This package or module name can be given to `pkg_resources.read_text`. -- maybe this helps: https://stackoverflow.com/q/6943182/ – sinoroc Nov 09 '20 at 08:43
  • Thanks for your answers. The code sample on the question was a bit simplified, the constructor is usually abstracted away from the client classes in the sense that the client classes only implement 1 method. It's not ideal but I ended up instantiating the Classes with a `__package__` object to use on the `pkg_resources`. – Mehdi Nov 14 '20 at 17:18

0 Answers0