Home > Blockchain >  Why it can not find the package from subfolder
Why it can not find the package from subfolder

Time:01-28

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.

CodePudding user response:

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

  • Related