Python imports without "from"

Issue

I have a project with the following directory structure:

dir1
–dir2
—-file1.py
—-file2.py
–file3.py

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.

Solution

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:

file3.py

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.

i.e.

from <dependency> import <class>

class App<Class>(<Class>):
    def overriden_method(self):
        return "my custom functionality"

References:

Answered By – Joshua Taylor Eppinette

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published