0

I am trying to call a Python file in another directory from the same package. I know that there are many similar posts, but I can't seem to make it work.

My directory looks like this:

├── PackageName    
│   ├── __init__.py (completely empty)   
│   ├── file_1.py  
│   ├── Folder 1  
│   │    ├── file_2.py   
│   │    ├── file_3.py  
│   ├── Folder 2  
│   │    ├── file_4.py   
│   │    ├── file_5.py 

I want any file be able to call any other file. So file_1.py can import classes from file_3.py which might rely on functions from file_4.py.

I would like to import things as such:
Within file_1.py
from Folder2.file_4 import class_4

within file_5 or file_3
from Folder1.file_2 import class_2
from file_1 import class_1

I've tried things like relative imports and adding __init__ to the other folders. I know I can use sys, but I would rather not.

Do I need to add something to my __init__ or is it something else completely?

Important
I would like to import like this regardless of which directory I am running from. For example, I would like to run file_5.py from the directory Folder 2.

9769953
  • 10,344
  • 3
  • 26
  • 37
James Kl
  • 177
  • 9
  • Does this answer your question? [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – Abhijit Sarkar Jun 30 '23 at 20:03
  • 1
    "I've tried things like relative imports and adding __init__ to the other folders.": that sounds exactly right. So if it didn't work, perhaps you coded that wrongly. – 9769953 Jun 30 '23 at 20:05

1 Answers1

0

It turned out I needed a __init__ in each of the sub directories. However, I think when I initially tried this, it did not work because I was copying the same blank init file into each directory. Rather I need to create a totally new init file.

James Kl
  • 177
  • 9
  • 1
    Copying an `__init__.py` fie should work just fine; so your copy possibly wasn't a proper copy. If you copied the file properly, there is no need to need to create one from scratch. – 9769953 Jun 30 '23 at 20:12