1

I have following project structure and i'm using PyCharm.

  • Project/
    • subproject1/
      • main.py
      • modules/
        • 1.py
        • __init__.py
    • subproject2/
      • main.py
      • modules/
    • subproject3/
      • __init__.py
      • file.py

I need in Project/subproject/modules/1.py a class from Project/subproject3/file.py. I tried it with from ...subproject3.file import class1, but then i get the error ValueError: attempted relative import beyond top-level package. Next i tried the import from subproject3.file import class1, and that work's, but i don't know why. My working directory in PyCharm is in Project/ but i tried to create a Python application with pyinstaller and that worked also for me and a received no error message. Why does my file 1.py knows from subproject3 and i can import it that way?

Thank you!!

niki1243
  • 11
  • 3
  • See [this answer](https://stackoverflow.com/a/64110410/1102805). – darcamo Oct 21 '20 at 14:06
  • Thank you for this link! It's a very good answer and cleared a few of my irritations.But why i get no error when i import from Project/subproject3/file with the command ``from subproject3.file import class1``?? Why does this works? – niki1243 Oct 22 '20 at 09:36
  • If the current working directory is `Project` or if the `Project` folder is added to `sys.path` then importing `subproject3` works because it is understood as a package, since it has a `__init__.py` file inside it. That is what tells python to treat `subproject3` as a package. On the other hand, importing `subproject1` or `subproject2` won't work since they are not packages, just regular folders. Add a `__init__.py` file inside them and you will be able to import from them. – darcamo Oct 22 '20 at 14:01
  • Okay thanks. I saw that in ``sys.path`` the ``Project`` folder is included in PyCharm. How i can know if the ``Project`` folder is included when i create a Python Application with pyinstaller? And when i try to execute the ``main.py`` in ``subproject1`` in the console the ``Project`` folder is not included and i don´t can fix it with adding the ``Project`` path to ``sys.path``. – niki1243 Oct 26 '20 at 15:47

0 Answers0