Reputation: 529
Still a bit new to making a application from scratch with python. Here is my file structure
Sudoku
|--__init__.py
|--game.py
|--__pycache__
|--components
|---__init__py.
|--board.py
|__pycache__(not sure how this got here?)
|--gui
|--__init__.py
|--gui.kv
|--solver
|--__init__.py
|--mysolver.py
I have a working Sudou game with my componets and gui modules being utilized in my game.py
. Now I am trying to write a sudoku solver that uses that inherits the Board
class I have (since it has some useful methods and has the board data).
In my solver.mysolver.py
, I have tried
from components.board import Board
which says "No module named components" which makes sense since they're not on the same level.
When I try from .components.board import Board
which I thought would work I get attempted relative import with no known parent package
. How can I let all my packages "know" what their parent package is? All my __init__.py
files are empty- should they not be? Also is there something wrong with my structure - I got a __pycache__
in my components
folder and I don't know why. I was testing my board.py
inside the components folder directly for a while - is that what created this?
Upvotes: 1
Views: 199
Reputation: 341
Lets say I want to import the from board.py, my import statement in game.py will be like
from components.board import <my_class_name>
pycache is the complied pyhton classes
Sudoku
|--__init__.py
|--game.py
|--__pycache__
|--components
|---__init__py.
|--board.py
|__pycache__(not sure how this got here?)
|--gui
|--__init__.py
|--gui.kv
|--solver
|--__init__.py
|--mysolver.py
Upvotes: 0
Reputation: 13087
Imports from outside of tree your current folder is the root of are tricky. To import from the parent folder or a sibling try starting your imports with:
import sys
sys.path.append("..")
This will add the parent folder to the path list of folders to look for modules in making your siblings visible. It is kind of gross, but it works for me as a quick fix.
When I first started using python I also ran into this layout issue. The temptation to want to have a runnable script like your solver that utilized all the same code. Python does not really want us to layout like this.
You would probably find it easer to work with things in general if mysolver.py was in the root folder with game.py.
Upvotes: 1