1

I created a function and tried importing it into another python script to do some unit tests. However I am constantly getting a ModuleNotFoundError. How do I properly import functions form one script to another?

My code:

from src.somefile import some_function

def test_somefunction:
    assert somefunction()

The error I encounter:

Traceback (most recent call last):
  File "test/test_file.py", line 2, in <module>
    from src.somefile import convert_epoch
ModuleNotFoundError: No module named 'src'

My folder structure:

project/
project/__init__.py
project/src
project/src/__init__.py
project/src/somefile.py
project/test
project/test/__init__.py
project/test/test_file.py

I would appreciate if someone could highlight what I am doing wrong and how I can neatly do an import. Thank you!

Xiddoc
  • 3,369
  • 3
  • 11
  • 37
Syabster
  • 99
  • 2
  • 9
  • yes. i run it in my project directory as python test/test_file.py – Syabster Jan 22 '20 at 04:26
  • Does this answer your question? [Importing files from different folder](https://stackoverflow.com/questions/4383571/importing-files-from-different-folder) – schwartz721 Jan 22 '20 at 04:28

2 Answers2

2

If you want to import modules like that you have to add directory containing your module to the PYTHONPATH environment variable OR you can use sys.path:

import sys
# assumed that /home/you/work contains `project` dir
sys.path.append('/home/you/work')
# now you can import

You can also use relative imports (import ..package) but they have some constraints (you can go up to a certain point) and are generally speaking a bad practice. Take a look at this article, it describes python's import statement in details: https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html

wikp
  • 1,123
  • 1
  • 8
  • 14
1

Hope this will work for you, assuming that you're running your script like this
python test/test_file.py

import sys
sys.path.append("..") # Adds higher directory to python modules path.

from src.somefile import some_function

def test_somefunction:
    assert somefunction()

Shibiraj
  • 769
  • 4
  • 9