0

Look at these 3 files and imagine they're stored in different folders:

#file1 in top_folder

from sub_folder.file2 import two
#file2 in top_folder/sub_folder

from file3 import three

two = 2
#file3 in top_folder/sub_folder

three = 3

Running file 2 directly doesn't throw an error.

Running file1 throws an error in file2 on the line from file3 import three. file2 can't find file3 and I think this is because the relative path is relative to file1 - not file2! I found a workaround - to use absolute paths like so:

#file2

exec(open("{path_to_file3").read())

But I'm convinced this isn't the best practice for overcoming the issue I'm describing. Are there other ways?

tonitone120
  • 1,920
  • 3
  • 8
  • 25
  • 2
    No. Import statements always search the Python path, period. If you want to use relative imports, you'll need to organize your project as a package. This question might be helpful: [Relative imports for the billionth time](https://stackoverflow.com/q/14132789/11082165) – Brian61354270 Jun 26 '22 at 19:12
  • Thanks for the response. I'm not really able to extrapolate the answers in that question to mine. Would you mind writing a post using my example? Esepcially the organising my project as a package. Would be really helpful – tonitone120 Jun 26 '22 at 19:38
  • Could you [edit] your question to include details about the directory structure of you project? There isn't much to package organization. Create a directory called `my_package`, put your Python files inside. You'll then be able to import modules as `import my_package.my_submodule.my_module`, or run then as `python3 -m my_package.my_submodule.my_module`. Relative imports would also become possible. Just make sure that the directory containing `my_package` _is_ on your Python path, e.g. by being your CWD. – Brian61354270 Jun 26 '22 at 20:10
  • @Brian I've added what folders these files would appear in – tonitone120 Jun 26 '22 at 22:02

2 Answers2

0

Specifying the path from the folder file1 is in solves it:

#file2

from top_folder.sub_folder.file3 import three
tonitone120
  • 1,920
  • 3
  • 8
  • 25
-1

Perhaps this is better:

#file2

import os
from pathlib import Path

absolute_path = str(Path(os.path.dirname(os.path.abspath(__file__)), '{folder_navigation_path_to_three.py}', 'three.py'))
exec(open(absolute_path).read())

Drawback: I use Pycharm and one of the great things about it is when you move about files it can automatically refactor all your imports. Pycharm won't refactor my code if I use this technique.

tonitone120
  • 1,920
  • 3
  • 8
  • 25