0
src\
    code\
         classes.py
         __init__.py
    test\
         tester.py

I have the following directory layout. I want to be able to run python tester.py as my driver command. tester.py would like to import some function or class from classes.py. I'm unable to do this for some reason. I tried doing relative imports, and a whole lot of other ideas, to the point of confusion now of what I'm doing. I would like a succinct way to do this. I've been able to do this if tester.py is a directory above classes.py, but I would like to have two separate folders in parallel like so. Any ideas?

turmond
  • 11
  • 1
  • "I tried doing relative imports" We can only tell you why this didn't work if you show us how you tried. However, you might want to look at [this question](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time?noredirect=1&lq=1). – Karl Knechtel Mar 29 '21 at 11:10

2 Answers2

0

Unfortunately this isn't how the Python import system works. Python imports modules (or parts or modules), rather than classes directly.

There is a full really good post here that details scripts vs modules and imports in full https://stackoverflow.com/a/14132912/2961873

apr_1985
  • 1,764
  • 2
  • 14
  • 27
0

You can always set environment variable PYTHONPATH to point to directory src allowing you to then import from package code. But an alternative would be to add the following code to the beginning of tester.py that adds whatever is the parent directory of the directory in which tester.py resides to the system path at runtime:

import os.path
import sys

# go up one directory level from this file's directory:
path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
# prepend parent directory to the system path:
sys.path.insert(0, path)

# now you can import from package code:
from code.classes import SomeClass
Booboo
  • 38,656
  • 3
  • 37
  • 60