0

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? :)

Theodor Peifer
  • 3,097
  • 4
  • 17
  • 30
  • 1
    try changing the name of utils `(/lib/python3.7/site-packages/utils/__init__.py)` it is conflicting with system utils package – user13966865 Jul 22 '20 at 09:51
  • Since you mentioned that you are facing issues with utils.py and the model.py could we see the imports for those two files? – Raymond C. Jul 22 '20 at 09:52

2 Answers2

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.

SirMizou
  • 88
  • 1
  • 4
  • 1
    Hi thanks it solved my problem, what does the . do? – CountDOOKU Apr 15 '22 at 10:18
  • It tells Python to use module in current package, in the original question the package is `src` (i.e. import utils from package src). [https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time](This SO thread) has great in-depth answers and links to documentation if interested to learn more, but in summary, relative imports are usable within packages – SirMizou Apr 16 '22 at 19:59
0

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')
Lorenzo Paolin
  • 316
  • 1
  • 5