Importing Python modules in large projects and "ModuleNotFoundError"

80 Views Asked by At

I have faced a rather famous issue while importing my python modules inside the project.

This code is written to replicate the existing situation:

  • multiply_func.py:
def multiplier(num_1, num_2):
    return num_1 * num_2
  • power_func.py:
from math_tools import multiplier

def pow(num_1, num_2):
    result = num_1
    for _ in range(num_2 - 1):
        result = multiplier(num_1, result)
    return result

The project structure:

project/
│   main.py    
│
└─── tools/
    │   __init__.py
    │   power_func.py
    │
    └─── math_tools/
        │   __init__.py
        │   multiply_func.py

I've added these lines to __init__ files to make the importing easier:

  • __init__.py (math_tools):
from .multiply_func import multiplier
  • __init__.py (tools):
from .power_func import pow
from .math_tools.multiply_func import multiplier

Here is my main file.

  • main.py:
from tools import pow

print(pow(2, 3))

Whenever I run it, there is this error:

>>> ModuleNotFoundError: No module named 'math_tools'

I tried manipulating the sys.path, but I had no luck eliminating this puzzling issue. I'd appreciate your kind help. Thank you in advance!

1

There are 1 best solutions below

0
Faruk Ahmad On

You messed it up in the "power_func.py" file. You have to use . before math_tools to refer to the current directory module.

Update "power_func.py" as bellow, it works perfectly.

from .math_tools import multiplier