Python imports without "from"


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

<other imports>

Alternatively, you can augment sys.path by using the PYTHONPATH environment variable:

$ PYTHONPATH=dir python3

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

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