Quantcast
Channel: Having Trouble with Import Statement in Python - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Having Trouble with Import Statement in Python

$
0
0

My current projects are structured like so.

python/    __init__.py    project_1/        __init__.py        program_1.py    project_2/        __init__.py        program_2.py    project_3/        __init__.py        program_3.py

I wanted to import a class from project_3/program_3.py, called INFO, from both project_1/program_1.py and project_2/program_2.py. In both my program_1.py and program_2.py, I've tried the following import statements that didn't work.

Edit - I typically "cd" into project_1 and run my program_1.py from there.

from project_3.program_3 import INFOTraceback (most recent call last):  File "./program_1.py", line 43, in <module>    from project_3.program_3 import INFOImportError: No module named 'project_3'from python.project_3.program_3 import INFOTraceback (most recent call last):  File "./program_1.py", line 43, in <module>    from python.project_3.program_3 import INFOImportError: No module named 'python'

The only way for me to import class INFO into program_1.py and program_2.py is by copying program_3.py in both program_1 and program_2's folder. My import in program_1 and program_2's statement would become:

python/    __init__.py    project_1/        __init__.py        program_1.py        program_3.py    project_2/        __init__.py        program_2.py        program_3.py    project_3/        __init__.py        program_3.pyfrom program_3 import INFO

This is quite inconvenience because now I have to update program_3.py in all 3 locations. Assuming my the way I structured my project folder is retarded:

  • What's the correct/best way to structure my folders so that I could call program_3.py from program_1/2.py?
  • If there's nothing wrong with my current structure, how do I correctly import the INFO class into program_1/2.py?

I have read the python documentation but it didn't say anything regarding importing classes from one subfolder to another. I also looked at another post from Stack Overflow as well but it didn't have the same structure as mine.

Update 1 - It's important to note that I'm merely using project_1/2 as folder to organized my projects. I originally had init.py in all my folders because I have no clue what I'm doing. The only module/package that I wanted to import in my project_1/program_1.py is from project_3/program_3.py. Example:

python/    project_1/        program_1.py    project_2/        program_2.py    project_3/        __init__.py        program_3.py

Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles



Latest Images