ahkam
ahkam

Reputation: 767

How to import a module from another package in python3?

Currently i'm having a file structure like below.

├── src
│   ├── common
│   │    ├──constants.py
│   │    └──configs.py
│   ├── utils
│   │    ├──module1.py
│   │    └──module2.py
│   └── service
│   │     ├──module3.py
│   │     └──module24.py
│   └── main.py
├── test
│   ├── utils
│   │    ├──test_module1.py
│   │    └──test_module2.py

My test_module1.py includes

# test_module1.py
import sys
sys.path.append("./.")

from src.utils.module1 import filter_file
from unittest import TestCase, main, mock

utils/module1.py includes

# module1.py
from common.constants import LOG_FORMAT, TIME_FORMAT
...

Here, when i try to run test_module1.py file from root i get an error saying that,

$- python3 test/utils/test_module1.py
$- ModuleNotFoundError: No module named 'common.constants'

what is the issue here

Upvotes: 0

Views: 172

Answers (1)

mnikley
mnikley

Reputation: 1645

Tested it, works like this on Windows:

├── src
│   └── utils
│        └──lib.py
├── test
│   └── utils
│        └──bla.py

lib.py:

def test():
    print("woo")

bla.py:

import os
import sys

sys.path.append(".." + os.sep + "..")

from src.utils.lib import test

test()

Upvotes: 1

Related Questions