DTK
DTK

Reputation: 115

Import packages with dependency of local modules in python

I am trying to understand how to import a module from a package from another folder in python, considering that this module imports a local module.

Say I have the following structure:


 C:.
│   e.py
│
└───src
    ├───a
    │   │   b.py
    │   │   context.py
    │   │   __init__.py
    │   │
    │   └───__pycache__
    │           context.cpython-38.pyc
    │
    └───c
        │   d.py
        │   f.py
        │   __init__.py
        │
        └───__pycache__
                d.cpython-38.pyc
                f.cpython-38.pyc
                __init__.cpython-38.pyc

Say I want to use the method (f.print_loca()) in b.py, currently running b prompts me:

Actual: 
Traceback (most recent call last):
  File "..\src\a\b.py", line 2, in <module>
    from b import f
  File "..\src\b\f.py", line 1, in <module>
    import d
ModuleNotFoundError: No module named 'd'

Expected: d->f

How could I fix this import error?

Below is what I have

b.py

from context import c
from c import f
f.print_loca()

context.py

import os
import sys

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
import c

d.py

def print_mes():
    print("d")

f.py

import d


def print_loca():
    print(d.print_mes()+"->"+"f")

Thank you

Upvotes: 0

Views: 880

Answers (1)

Sensei Munk
Sensei Munk

Reputation: 136

Try using "." before start so:

if you were to import d into b i would do something like:

from .src.c.d import *

# or from .src.c import d

# or import .src.c.d

Also it's better practice to only sys reference project root dir i think.

Upvotes: 1

Related Questions