1

I've been looking for it already answer in stackoverflow, but i didn't find a solution.

I use the 3.6.2 version of python and I have a folder structure like this

backend
  |   __init__.py
  |
  |------- entity_extraction\
  |           __init__.py
  |           main.py
  |------- index\
  |           __init__.py
  |           main.py
  |------- lib\
  |           __init__.py
  |         |--- db\
  |           __init__.py
  |------------   |--- models\
  |                   __init__.py
  |                   model.py

If I import model.py from main.py in the index folder in this way and run python main.py:

from backend.lib.db.models import *

I have this error:

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    from backend.lib.db.models import *
ModuleNotFoundError: No module named 'backend'

How I import in absolute way a module that is in a folder outside the current run script folder? The only way that works is import sys and add the uplevel folder path, but seems an hack.

Thanks!

skytron87
  • 91
  • 1
  • 10
  • If you have a standard folder where all your packages are in, consider creating a `.pth` text file in your `python/Lib/site-packages` folder (Windows), that contains the absolute path of your folder. This will do the `sys.path.append` for you automatically everytime you run the interpreter. See https://docs.python.org/3/library/site.html – Jeronimo Apr 25 '18 at 10:08
  • Have you seen https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa or other similar questions? – Mazdak Apr 25 '18 at 10:09
  • There isn't a way to import in a cleaner way? I saw the django project and use the import absolute. How do they do it? @Kasramvd – skytron87 Apr 25 '18 at 19:50
  • @skytron87 The logic behind your importing is kind of in a contradict with Python's importing policies. There are actually many reasons for that, one of which is the possibility of having a circular import. For that reasons, you have to explicitly add the path in which you want to import to the `sys.path` or other things that have a similar effect. – Mazdak Apr 25 '18 at 20:28
  • So the pure absolute import doesn't exists? Thank you for your time @kasramvd – skytron87 Apr 25 '18 at 20:41
  • It does but in its proper situation. I'd recommend you to read https://docs.python.org/3/reference/import.html#the-import-system and https://www.python.org/dev/peps/pep-0366/ so that you can find the answer of your question thoroughly. – Mazdak Apr 25 '18 at 20:50
  • Thank so much for your time... @Kasramvd – skytron87 Apr 25 '18 at 20:52
  • @skytron87 You're welcome ;). – Mazdak Apr 25 '18 at 20:54

0 Answers0