1

I'm trying to import a class that is allocated in a higher folder.

This is my folder structure

--proyect
  --folder1
    -class1.py
    --connection_foler
      -conn.py
  --folder2
    -anotherclass.py
    --configfolder
      -app.py

I want to access to the conn class that is in conn.py and access to the class allocated in anotherclass.py from app.py

I found a lot of solutions but I'm not sure what is the correct way to do this because some solution talks about use SO module and the other one's talks about use sys module.

Any help with this?

Thanks a lot.

Reco Jhonatan
  • 1,503
  • 4
  • 23
  • 35
  • Please look into the concept of "__init__.py" file, this will help you. https://stackoverflow.com/questions/448271/what-is-init-py-for – Deepak Jul 28 '20 at 23:28
  • @Deepak I *think* it's not considered good practice to use `__init__.py` for importing internally within a project like this... or it possibly doesn't even work in all circumstances. – Tim Jul 28 '20 at 23:38
  • Does `from proyect.folder1.connection_foler.conn import conn` work? – Tim Jul 28 '20 at 23:40
  • What I have experienced is that this makes your project absolute path independent. Yes, sometimes it becomes trickier on how to reference files from some nested folder. But worth tri-able in the problem given. Looking forward for other answers also. – Deepak Jul 28 '20 at 23:43
  • Hi @Tim "not module named proyect" error appears – Reco Jhonatan Jul 28 '20 at 23:43
  • What matters is what is in your PATH. You should be installing your project from the root directory, then it should be accessible – juanpa.arrivillaga Jul 29 '20 at 00:09
  • 1
    Note, also, `.py` files correspond to *modules*. You don't import *classes*, you import *modules* – juanpa.arrivillaga Jul 29 '20 at 00:10
  • @RecoJhonatan are you sure you've spelled things correctly? It looks like `proyect` ought to be `project`, but I'm not sure if you mis-spelled it just in your question, or if you mis-spelled it in your actual folder names as well. Similarly `connection_folder` ought to be `connection_folder`. As @juanpa.arrivillaga said, what matters is what's in your PYTHONPATH. Depending how you're running `app.py` and where you're running it from, the things you need may have automatically been added to your PYTHONPATH but they might not, which could be the issue here. How are you running `app.py` exactly? – Tim Aug 03 '20 at 16:20

0 Answers0