0

This is my project structure:

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

second.py

def hello():
    print('hello')

first.py

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Sahar
  • 89
  • 9
  • Please do not edit questions to include an answer. Keep in mind that this is a Q&A site; we want clear questions that stand *as questions* to suit the format. This is **not a discussion forum** so we don't "update" the OP to show progress or indicate that a problem was solved; we only edit it for clarity and tone. – Karl Knechtel Dec 24 '22 at 16:57

2 Answers2

1

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".

S.B
  • 13,077
  • 10
  • 22
  • 49
-1

There are several sources for this error but, probably, if your project directory is my_project then you don't need .. in the import statement.

from second_folder import second
Akbari
  • 31
  • 2
  • You mean: ```from second_folder import second``` ? – Sahar Dec 24 '22 at 16:22
  • `my_project` directory is the root folder but it's not in the path. That's because `first.py` is not directly inside `my_project` folder. The only path that gets inserted into `sys.path` is `first_directory` - the directory of the script. – S.B Dec 24 '22 at 16:46