Search code examples
pythonpython-3.xpython-importimporterrorpython-module

ModuleNotFoundError when importing my own python module


so the problem is that when I try to import something from the module I created, I run into ModuleNotFoundError: No module named '<my_module>'.

My project structure is just like this one:

├── first.py
└── some_dir
    ├── second.py
    └── third.py

You can replicate the problem with these 3 files:

third.py

""" This is the third file and we store some variable here
    that will be imported to the second """

a = 69

second.py

"""This is the second file. We import 
    a variable from the third and calculate
    the sum of a and b"""

from third import a
b = 10
sum = a + b

first.py

"""This is the first and final file 
    where everything comes together"""
from some_dir.second import c

print(c)

And when I run first.py I get error:

Traceback (most recent call last):
  File "/home/username/moo/goo/foo/first.py", line 3, in <module>
    from some_dir.second import c
  File "/home/username/moo/goo/foo/first.py", line 5, in <module>
    from third import a
ModuleNotFoundError: No module named 'third'

Solution

  • You could use relative imports:

    from .third import a
    
    c = a + b
    

    change sum to c since that's what you're importing.

    Keep in mind that the code above won't work if you execute second.py directly because ImportError: attempted relative import with no known parent package