简体   繁体   中英

Can I make imports always relative to the file the import statement is found in?

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?

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

#file2

from top_folder.sub_folder.file3 import three

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM