0

My Directory is structured as follows:

superParent
│   app.py
├───custom_package
       file1.py
       file2.py
       file3.py
       file4.py
       __init__.py

I am running app.py I want to import functions from file1.py and file2.py into app.py. I also import functions from file3.py and file4.py in file1.py and file2.py.

Now when I include

from custom_package.file1 import func_abc

in app.py it throws an ModuleNotFound error. However,

from custom_package import file1
func_abc = file1.func_abc

works perfectly.

Similarly, when I am trying to import a function from file3.py into file1.py using:

from file3 import func_efg

in file1.py it throws an ModuleNotFound error. However,

from custom_package import file3
func_efg = file3.func_efg

works perfectly in file.py.

I have found a lot of similar questions in StackOverFlow, however, none of them addressed this peculiar (for me - not for everyone) behaviour. A lot of them suggest making changes to the PYTHONPATH or sys.append('path\to\custom_package') (while strongly arguing that we should not resort to this). How do we solve these import-related issues to import particular functions from custom-defined local packages from a relative directory (preferably without messing with sys.path at all)?

Additional Context (not sure if this is necessary): I will be containerizing this and deploying the container to AKS.

Some additional StackOverflow questions which have addressed similar issues:

  1. Can't import my own modules in Python
  2. Importing files from different folder
  3. ImportError: No module named <something>
  4. Importing files from different folder
  5. Importing modules from parent folder
  6. How to do relative imports in Python?
  7. relative import in Python 3
Anirban Saha
  • 1,350
  • 2
  • 10
  • 38

1 Answers1

0

I would suggest to use the leading dot format for package relative imports

And also to add your submodules (file1, file2, etc) to custom_package/__init__.py as it is showed here: submodules

pbacterio
  • 1,094
  • 6
  • 12
  • The leading dot format solved my issue to import functions from file3 and file4 into file1 and file2. For importing into app.py it is throwing an error `ImportError: attempted relative import with no known parent package` – Anirban Saha Sep 08 '21 at 07:18