0

I have a Python directory like this, and I am running main_script.py from src.

Whenever I try to import classes from class_files into main_script.py, I get an error. How do I properly do that?

 - src/
   - jobs/
   - _init_.py
    - my_team/
      - _init_.py
     - my_project/
       - _init_.py
       - main_script.py
      - class_files/
        - class1.py
        - class2.py
        - class3.py
        - __init__.py

I already tried doing an absolute import, which also did not work.

from jobs.my_team.my_project.class_files import *

thewhitetie
  • 303
  • 2
  • 12
  • I think the solution to your question is similar to this... https://stackoverflow.com/questions/1260792/import-a-file-from-a-subdirectory – kr3mbo Aug 11 '20 at 12:01

1 Answers1

0

jobs.my_team.my_project.class_files would only work if each of those constituent parts is a Python package. Eg,

src/
    jobs/
        __init__.py
        my_team/
            __init__.py
            my_project/
                __init__.py
                main_script.py
                class_files/
                    class1.py
                    class2.py
                    class3.py
                    __init__.py

Your import tree must be made up of Python packages. If it doesn't have __init__.py in it, that directory is not a Python package. Simple as that.

Also, for this to work, your src/ directory needs to be in the $PYTHONPATH environment variable or be added to sys.path at runtime.

Ken Kinder
  • 12,654
  • 6
  • 50
  • 70
  • I tried adding __init__.py to `src` and everywhere else, but that didn't help. I also did sys.path.insert(0, './src') – thewhitetie Aug 11 '20 at 13:22
  • you would only add `__init__.py` to `src` if you want to make `src` a package. And adding a relative path to sys.path isn't going to work; it needs to be absolute. – Ken Kinder Aug 11 '20 at 13:46