1

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?

3
  • 1
    Couldn't you pass the configuration filepath to the class and supercall init method, save it in a class variable and use it? Commented Nov 8, 2020 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: stackoverflow.com/q/6943182 Commented Nov 9, 2020 at 8: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. Commented Nov 14, 2020 at 17:18

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.