Hi Karl,
thank you very much for all of your time and attempting to resolve this issue.
My misinterpretation is all. I create my folders/directories via Windows. This is not the only way of course. You can of course create them via DOS or Linux as you know. I was just a bit concerned why you were doing it differently and thinking there was a more sinister reason for doing so (there isn’t, just preference I suppose).
Well, I have found where I went wrong. The relative import syntax from my original post is not wrong at all. The issue was that I was attempting to run that module from its location that was the issue. From Learning Python, 5th E.:
In Python 3.X, the new relative search rule change means that a file can no longer
serve as both script and package module as easily as it could in 2.X.
In order to test/run the relative imports instructions, you must implicitly run them from a main module, …, the main of the package. So, I have added a root_main.py
module to the project. If I run the project from there, no exception errors are encountered. Here is my updated package:
From the figure, I was attempting to run the file_1.py
module in the package1 directory. This is what was causing the errors (as highlighted by the Learning Python reference). I went ahead and added a new module named root_file.py
. When I ran the script from there, all was well. In other words, I was attempting to run the module as the package script. Of course, this module is a package module and not the script of the package, hence the exception errors.
In my new module root_file.py
, I have the following script:
from package1 import file_1
file_1.run_1('Hello from the pkg\root_file.')
The script in my file_1.py
file, I have:
from . import file_2
from .sub_package1 import sub_file_1
num1 = 11
string1 = "I'm in package1, file_1."
def run_1(message):
print(message)
run_1(string1)
Here is the YouTube video that I referenced. Note that it discusses both the absolute and the relative import methods. If you want to skip to the beginning of the relative imports discussion, jump to the ~5:35 minute mark.
The limitation of relative imports is that you can only import modules that are along the hierarchy (above and below) but not adjacent. For example, with relative import syntax, I wouldn’t be able to import modules from the package2 directory. For that, you have to use absolute path imports.
Well, thank you again for your time and attempting to resolve this issue. Much appreciated!
All is well now.