1

I want to use my Python "toolbox" - packages I've written myself - in several other packages (let's call them pkg1 and pkg2 in the example below).

Here is what my work directory looks like:

└── WORK
    ├── PythonToolBox
    │   └── Tool1
    │       └── module1.py 
    ├── Use1
    │   └── pkg1
    │       └── p1_script.py
    └── SomeSubdirectory
        └── Use2
            └── pkg2
                └── p2_script.py

Let's say I want to import module1.py, from the package Tool1, into p1_script.py and p2_script.py.

Because of the architecture of my directories shown above, I believe I would need to write the following bit of code in p1_script.py:

from pathlib import Path
import sys
path_root = Path(__file__).parents[2]
sys.path.append(str(path_root))
            
import PythonToolBox.Tool1.module1 as mod1

and do the same in p2_script.py, except that I'd need to make the following modification to the snippet of code above : Path(__file__).parents[2] --> Path(__file__).parents[3].

That works, but it makes it hard to share work with others : I'd need to copy module1 into pkg1 before sending it to someone else, and remove the snippet of code to write import module1.py as mod1 instead.

Another option would be to copy module1.py into pkg1 and pkg2 at the beginning. However, this doesn't seem like a good option either, as that would create two different versions of module1: I might improve module1 as I'm working on pkg1, and now pkg2 won't benefit from these improvements.

Is there a better solution to use that toolbox than the two I've listed above?

Banjo
  • 11
  • 2
  • Take a look at https://stackoverflow.com/a/20749411/9842129 and https://stackoverflow.com/a/2349998/9842129. You may want to look at "importlib" docs – iamakhilverma Jun 14 '22 at 09:14
  • @mrVerma : I've read through both of your links, and while they describe several methods of importing modules, I don't think any brings more functionality or simplicity to the method I describe which changes sys.path. In all the cases they describe, I believe you still need to specify path, whether absolute or relative, which makes sharing work with colleagues difficult. My question is more about organization than import : I'm surprised that I can't find a "canonical" way of using my own packages as modules in several other scripts without copy-pasting them or having to write specific paths. – Banjo Jun 14 '22 at 11:48

0 Answers0