0

I met a strange problem in python package. I have a python package named manchinetranslator in which I created a subfolder for unit tests as shown below.

manchinetranslator/translator.py
manchinetranslator/__init__.py
manchinetranslator/tests/tests.py

In translator.py, two functions are defined as:

def english_to_french(text):
...
def french_to_english(text):
...

The init.py is:

from . import translator

The tests.py contains unit tests of the two functions in translator.py and is as follows:

import unittest
from translator import english_to_french, french_to_english
class Test_english_to_french(unittest.TestCase):
...   
class Test_french_to_english(unittest.TestCase):
...

But when running tests.py, it gives an error as follows:

Traceback (most recent call last):
  File "C:\Python\manchinetranslator\tests\tests.py", line 3, in <module>
    from manchinetranslator.translator import english_to_french, french_to_english
ModuleNotFoundError: No module named 'manchinetranslator'

However, when tests.py is put in the same folder as translator.py, it works fine. I guess it may need to set $PYTHONPATH, but I am not sure how to do it. So I need help with this problem.

E Zhang
  • 185
  • 7

1 Answers1

2

You are trying to import from the parent directory, that won't work. tests.py cannot import from translator because it is inside it.

See this SO answer instead for what to do: https://stackoverflow.com/a/24266885/30581

Emrah Diril
  • 1,687
  • 1
  • 19
  • 27
  • What should be included in the __init__.py in tests folder? There is no module to import in the tests folder, only a unit test file that is not called. – E Zhang Jan 28 '23 at 05:30
  • You can leave it blank. Even though it is blank, it has to exist. I added this info to my answer. You can read more information here: https://crunchingthedata.com/python-init-file/ – Emrah Diril Jan 28 '23 at 05:31
  • 1
    Official docs: https://docs.python.org/3/tutorial/modules.html#packages – OneCricketeer Jan 28 '23 at 05:37
  • No, it does not work with the same error. – E Zhang Jan 28 '23 at 05:40
  • Oh you are trying to import a method from the parent directory. That's not possible. I changed my answer – Emrah Diril Jan 28 '23 at 05:42
  • By the link of @OneCricketeer, it confirms my guess. The subfolder must be in the sys.path because "When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.". – E Zhang Jan 28 '23 at 05:47
  • @user103 see my answer, I updated it to point to another SO answer. – Emrah Diril Jan 28 '23 at 06:09