'Can't import file from another directory which imports a file from the same directory (int Python)

So my project structure is the following:

project/
    src/
        __init__.py
        utils.py
        model.py
    usage.py

I now want to import functions from utils.py and a class in model.py into my usage.py. But the model.py itself imports functions from utils.py.

So I am doing the following:

# usage.py

from src.model import Model
from src.utils import onehot_to_string

But I am getting the error that it couldnt import functions from utils.py into the model.py:

File "usage.py", line 11, in <module>
    from src.model import *
  File "/project/src/model.py", line 7, in <module>
    from utils import onehot_to_string
ImportError: cannot import name 'onehot_to_string' from 'utils' (/lib/python3.7/site-packages/utils/__init__.py)

I think I am lacking of some basic Python packaging knowledge here. Can someone help me out? :)



Solution 1:[1]

Looks like python can't find your utils file in model.py. Then it proceeds to search for utils in path and finds it because, for example, someone has installed some library named utils. Then, the error occurs because this previously installed utils library has no onehot_to_string function.

Try to change your from utils import onehot_to_string to from .utils import onehot_to_string in model.py to use relative import.

Solution 2:[2]

for file/function/variables importing use this sys method

import sys
# insert at 1, 0 is for other usage
sys.path.insert(1, '/path/to/application/app/folder')

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 Lorenzo Paolin