Search code examples
pythonmodel

ModuleNotFoundError: No module named 'utils' from utils import edit_distance


from utils import edit_distance

Error: ModuleNotFoundError: No module named 'utils'

from utils import edit_distance - I have imported it in a .py file. utils folder is in the same branch with training folder which contains .py file that I import edit_distance from utils:

path_image


Solution

  • At first I would suggest you should try a hard import for the file and check if it works.

    import path.to.utils.edit_distance
    

    Though from what I saw (in the picture you linked) you are using the init.py file, but it needs to have something inside it for you to be able to import what you want. You can have a look at how python handles packages.

    In short, you need to import the file first in the __init__.py of the utils folder, so you can import utils like a module.

    You can do that from a relative import, like so:

    #utils/__init__.py
    
    import .edit_distance
    

    Why you need to do this? Well python, when you import a directory, tries to look for an __init__.py file, if there is one, it runs it to initialize the "module". So when you say from "module" import "smt", that "smt" had been imported and then initialized in the __init__.py of the "module". Try to experiment on how it works.