1

I am trying to import a python class from another directory but it keeps showing "module not found"

MLJAR-SUPERVISED
├── examples
│   │── notebooks
│   └── scripts
│          └── target.py
└── supervised
    └── source.py

I am trying to import a class evaluation from source.py to target.py with this:

from supervised.source import evaluation

but it shows `ModuleNotFoundError: No module named 'supervised' What is the best way to do this in python 3.9 ?

Henry Harutyunyan
  • 2,355
  • 1
  • 16
  • 22
aakarsh
  • 423
  • 1
  • 6
  • 15

2 Answers2

3

There are multiple ways to work around this. First way is to move the supervised folder containing source.py into the scripts folder. So the file structure would look something like this:-

MLJAR-SUPERVISED
├── examples
   │── notebooks
   |── scripts
           |── target.py
           └── supervised
                  └── source.py

The second way is extensively answered here...link

CYBERDEVILZ
  • 315
  • 1
  • 11
  • this did work but I would really want to know why my approach was not right? – aakarsh Jul 31 '21 at 17:07
  • 1
    When you **import abc** , Python will check for the module abc in `sys.modules`. This is a cache of all modules that have been previously imported. If the name isn’t found in there, Python will proceed to search through a list of built-in modules. These are modules that come pre-installed with Python. If the name still isn’t found in the built-in modules, Python then searches for it in a list of directories defined by `sys.path`. This list usually includes the **current directory**, which is searched first. Since your package is present in a different directory , hence error occurs. – CYBERDEVILZ Jul 31 '21 at 23:21
0

You should make a new file in the supervised folder called __init__.py(exactly)
and then you will be able to import classes with from supervised.source import evaluation.

xkcdjerry
  • 965
  • 4
  • 15