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

Import error when trying to import python module from other folder

This is my project structure:

/my_project
    /first_folder
        first.py
    /second_folder
        second.py

second.py

def hello():
    print('hello')

first.py

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

from ..second_folder import second

second.hello()

when i run first.py i get the following error:

ImportError: attempted relative import with no known parent package

How can I avoid this problem?

>Solution :

Normally when you run your script as the main module, you shouldn’t use relative imports in it. That’s because how Python resolves relative imports (using __package__ variable and so on…)

This is also documented here:

Note that relative imports are based on the name of the current
module. Since the name of the main module is always "__main__",
modules intended for use as the main module of a Python application
must always use absolute imports.

There are ways to make this work for example by hacking __package__, using -m flag, add some path to sys.path(where Python looks for modules) but the simplest and general solution is to always use absolute imports in your main script.

When you run a script, Python automatically adds the directory of your script to the sys.path, which means anything inside that directory (here first_folder is recognizable by interpreter. But your second_folder is not in that directory, you need to add the path to the my_project(which has the second_folder directory) for that.

Change your first.py to:

import sys

sys.path.insert(0, "PATH TO /my_project")

from second_folder import second

second.hello()

This way you can easily go into first_folder directory and run your script like: python first.py.

Final words: With absolute imports, you don’t have much complexity. Only think about "where you are" and "which paths are exists in the sys.path".

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