0

I am trying to create a package for my own use and cannot seem to be able to import a class into another folder. Here is a image of my current directory.

enter image description here

I am trying to import a class from strategies.core into my test/test_symbol.py file but it keeps giving me an ModuleNotFoundError

Error

Traceback (most recent call last):
File "c:\Users\Francois\Desktop\H4Impulse\test\test_symbol.py", line 6, in <module>
from strategies.core import Symbol
ModuleNotFoundError: No module named 'strategies' 

test_symbol.py

import unittest
# import sys
# sys.path.append(r"C:\Users\Francois\Desktop\H4Impulse")


from strategies.core import Symbol
# from ..strategies.core import Symbol <--- this also doesn't work
class TestSymbol(unittest.TestCase):
    pass



unittest.main()

it works when I use sys.path.append to append the path but I feel like this shouldn't be necessary. Any help would be appreciated.

Francois Paulsen
  • 135
  • 1
  • 10
  • 1
    Since you are running "\test\test_symbol.py", I assume your working directory might be "\test", thus it is not finding the `strategies` module within that folder. Can you confirm your working directory? – ALai Jul 19 '21 at 13:32
  • Did you tried from .strategies.core import Symbol (with a single dot) to go one level up he directory – Vignesh Jul 19 '21 at 13:34
  • 1
    How are you invoking `test_symbol.py`? You should do it from the project level directory. You should probably also use [test discovery](https://docs.python.org/3/library/unittest.html#test-discovery) rather than call the test script directly. – suvayu Jul 19 '21 at 13:34
  • Did you tried from .strategies.core import Symbol (with a single dot) to go one level up he directory – Vignesh Jul 19 '21 at 13:35
  • I did not execute the file from the project level directory. Thank you for the help – Francois Paulsen Jul 19 '21 at 13:45

1 Answers1

0

Problem lies in your path. You are using:

  • absolute path in sys.path.append
  • relative path in your import

Probably if you call sys.path.append(r"./") it would raise the same ModuleNotFoundError error.

Since you are running the script "c:\Users\Francois\Desktop\H4Impulse\test\test_symbol.py", your working directory is probably set as "c:\Users\Francois\Desktop\H4Impulse\test". In this folder, the module strategies does not exist.

Finally, you should either:

  • Set "c:\Users\Francois\Desktop\H4Impulse" as your working directory (suggested if it is THE directory of your project)
  • Use relative imports
ALai
  • 739
  • 9
  • 18