I have a project with the following directory structure:
In file3, I call a function in file1. In file1, it calls a function in file2, so it imports file2. Other files in dir2 are also imported by file1.
Currently, file1 causes a ModuleNotFound error on the line
import file2. This can be resolved by changing it to
from dir2 import file2, but the issue is I would need to go through all the files in dir2 and try to fix the imports.
dir2 is a project found on Github and I would really not want to change all the imports every time I pull any changes. Is there a way to import file2 for use in file1, without having to change the imports?
I am using Python 3.9.12.
Python performs module resolution based on the
sys.path variable. You can append
dir2 to this path so that any imports within it can be resolved:
import sys sys.path.append("dir") <other imports>
Alternatively, you can augment
sys.path by using the
PYTHONPATH environment variable:
$ PYTHONPATH=dir python3 file3.py
Keep in mind that path modifications are typically a code smell and should only be used when absolutely necessary. You can most likely resolve the root problem by having this "directory" (third party dependency) included in your project as a true pip installed dependency, then it will be "on path". Beyond that, you should only override third party code through your first party modules, not by adding files directly into their directories.
from <dependency> import <class> class App<Class>(<Class>): def overriden_method(self): return "my custom functionality"
Answered By – Joshua Taylor Eppinette