'ModuleNot FoundError : No module named 'lib'

I am trying to understand import mechanism behind python but this piece of code gives error.

Here is my folder structure:

import_test
  -calculator
   ..__init__.py
   ..operation.py
  -lib
   ..__init__.py
   ..multiply.py

It is working when i ran on PyCharm IDE, but if i run from command line like

'py operation.py'(for now windows,for the next phase i will try on raspbian RPi)

i am getting module not found error! Tried many ways from forums on internet but still no progress.

multiply.py:

def multiplier(a,b):
    return a + b

operation.py:

from lib.multiply import multiplier
print (multiplier(3,4))

lib/init.py:

from .multiply import multiplier

This is the output of my running:

File "operation.py", line 1, in <module>
    from lib.multiply import multiplier
ModuleNotFoundError: No module named 'lib'


Solution 1:[1]

To go up a directory, to another directory, and back down, almost always requires editing the sys.path pycharm tends to do this automatically for a project, without really telling you it did.

using the structure you have in the question this should work:

import_test
  -calculator
   ..__init__.py (EMPTY FILE)
   ..operation.py
  -lib
   ..__init__.py (EMPTY FILE)
   ..multiply.py

operation.py:

import os
import sys

# insert the "import_test" directory into the sys.path
sys.path.insert(1, os.path.abspath(".."))

from lib.multiply import multiplier

print (multiplier(3,4))

multiply.py:

def multiplier(a,b):
    return a + b

Running operation.py returns:

7

Solution 2:[2]

This is because when you are starting up your script from calculator directory, so python add's import_test/calculator to the sys.path, but it doesn't know anything about the lib.

You can either follow @tgikal advice and add parent directory to the sys.path but it looks like an ugly hack. Better way to handle this is to run your script like this

python -m calculator.operation, you might need to add an empty __init__.py file to the import_test directory, depends on your version of python.

Solution 3:[3]

In my case, I had copied some code from another project that had user built modules in the imports at the top of the code, but I did not copy this user built module to my new project. I found this needed lib module folder in the original project and copied it to get rid of the message.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Vlad
Solution 3 questionto42standswithUkraine