How to import a module from another folder in Python?

I have a project that I want to structure as follows:

myproject
  __init__.py
  api
    __init__.py
    api.py
  backend
    __init__.py
    backend.py
  models
    __init__.py
    some_model.py

Now I want to import some_model.py module into api.py and backend.py. How to do it right? I tried

from models import some_model

but this is not with “ModuleNotFoundError: There is no module named“ models. ”I also tried

from ..models import some_model

which then gave me "ValueError: an attempt to relative import beyond the top-level package." What am I doing wrong here? How to import a file from another directory that is not a subdirectory?

+4
source share
4 answers

Firstly, this is an expression of an import statement:

from models import some_model

should be indicated:

# in myproject/backend/backend.py or myproject/api/api.py
from myproject.models import some_model

, myproject, /path/to/parent sys.path. , :

export PYTHONPATH=/path/to/parent

, , , setup.py . PyPA. , setup.py , sys.path:

pip install --editable .
+2

, Python , . ! !

python sys, Python, Python , .

:

import sys
sys.path.insert(0, '/path/to/application/app/folder')
import [file]

sys , .

!

.

0

, , . -, , script, .

, script (, main.py) , (api.py backend.py ),

from models import some_model

.

-1

: . :

import os

os.chdir( '// ")

, . , .

Allen

-2
source

Source: https://habr.com/ru/post/1694265/


All Articles