Python: name of a parent package not recognized in import statements

I understand that there are many questions on this topic, but most of the answers that I have seen describe complex workarounds for problems that should, it seems to me, be simple. Here is my directory structure:

Mapper/
    LICENSE.txt
    README.txt
    setup.py
    bin/
        # nothing here, yet
    mapper/
        __init__.py
        process.py
        where.py
        # ...
        binconvert/
            __init__.py
            tocsv.py
            todict.py
            # ...

I would like to use absolute paths for all my locally designed modules to reduce confusion and avoid the errors mentioned here .

However, I have a few problems with this. When I run process.py, in which I import tocsv.py, for example,

from mapper.binconvert import tocsv

I get an error: ModuleNotFoundError: No module named 'mapper'

I know what I could do from binconvert import tocsv, but, as I said, I try to ensure that all my locally developed modules import absolute paths.

, , tocsv.py, where.py :

 from mapper import where

, import, , . , , python :

( ), , siblings. , sound.filters.vocoder sound.effects package, sound.effects import echo.

sound/                          Top-level package
      __init__.py               Initialize the sound package
      formats/                  Subpackage for file format conversions
              __init__.py
              wavread.py
              wavwrite.py
              aiffread.py
              aiffwrite.py
              auread.py
              auwrite.py
              ...
     effects/                  Subpackage for sound effects
              __init__.py
              echo.py
              surround.py
              reverse.py
              ...
     filters/                  Subpackage for filters
              __init__.py
              equalizer.py
              vocoder.py
              karaoke.py
              ...
+4
3

process.py, mapper. Python , sys.path, , ["standard python path", "Mapper/mapper"].

python mapper ( mapper).

:

  • : from .binconvert import tocsv ( PEP 328)
  • 1 process.py Mapper
  • PYTHONPATH process.py, Mapper
+3

"mapper" ( "from mapper.anything import that" ), , "mapper", sys.path:

# in process.py
import os, sys
THIS_DIR = os.path.dirname(os.path.abspath(__file__)) #  "mapper" dir
MAPPER_ROOT_DIR = os.path.dirname(THIS_DIR) #  points to "Mapper" dir
if MAPPER_ROOT_DIR not in sys.path:
    sys.path.insert(0, MAPPER_ROOT_DIR)

, . ( - "" ). sys.path .

-1

Add your module directory to PYTHONPATH:

Internal Code:

import sys
sys.path.append("/path/to/your/module")

or on the command line:

export PYTHONPATH=$PYTHONPATH:/path/to/your/module
-1
source

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


All Articles