2

I have the following folder structure:

src
 |_ __init__.py
    example.py
test
 |_ test.py
# __init__.py
class API:
    def something(self):
        print('folder src | file __init__')
# example.py
class Example:
    def doingSomething(self):
        print('folder src | file example')
# test.py
import src
from src.example import Example

class Test:
    def somethingElse(self):
        print('folder test | file test')

when I run the test.py file, I get the following error:

Traceback (most recent call last):
  File "<my path>\test\test.py", line 1, in <module>
    import src
ModuleNotFoundError: No module named 'src'
Little Ball
  • 5,728
  • 3
  • 7
  • 26
  • 1
    If you are using PyCharm, check my answer to get it configured correctly: https://stackoverflow.com/a/76055855/1563072 – Zitoun Apr 19 '23 at 14:45

2 Answers2

1

Unless you import the example module in your src/__init__.py file, you need to specify the module name (i.e., example) within the package (i.e., src).

from src.example import Example
abc
  • 11,579
  • 2
  • 26
  • 51
  • ok thanks, but I'm still getting the same error from the first line of test.py – Little Ball Dec 19 '20 at 20:39
  • 1
    That means that the src package is not in your `PYTHONPATH` – abc Dec 19 '20 at 20:42
  • How do I put it in my PYTHONPATH? I'm using vscode – Little Ball Dec 19 '20 at 20:43
  • [This question](https://stackoverflow.com/questions/53653083/how-to-correctly-set-pythonpath-for-visual-studio-code) or [this one](https://stackoverflow.com/questions/58570503/how-to-use-pythonpath-with-vscode-python-extension-for-debugging) might be useful. – abc Dec 19 '20 at 20:50
  • 1
    try using the below import sys sys.path.append('../') – Mandar Autade Dec 19 '20 at 20:52
  • What should I add in my `.vscode/settings.json` file? I am on windows 10. The import sys didn't work and I can't find an answer on both links posted by @abc – Little Ball Dec 19 '20 at 21:02
-2

You don't actually need to include the "src" folder in your path. For example, if you're folder structure looks like this:

  • src
    • app1

      • models1.py
      • views1.py
    • app2

      • models2.py
      • views2.py

You can import models2.py into views2.py like this:

from .models2 import ClassName
Code on the Rocks
  • 11,488
  • 3
  • 53
  • 61