Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python imports without "from"

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading