I want this structure:
Zimp/controller/game_play -->How do I: import Zimp/model/game_play module in the easiest way? Zimp/model/game_play
I made a folder called controller and a folder called model. Within those folders I put an empty __init__.py file (don't know why that would do anything). I didn't make a model.py file or a controller.py file. It didn't work. I just made a model.py and a controller.py that are empty except for the main block that automatically appears when creating a new module. No difference.
In controller/game_play.py I tried: from ..model import game_play_model
It says value error: attempted relative import in non-package
Is the idea not to actually put them in separate directories? What is the norm?
Thanks
2 Answers 2
The problem is you're trying to execute a subpackage module directly, see answers to the question Attempted relative import in non-package even with __init__.py.
First I think you need to set up your directory file structure like this:
Zimp/ top-level package
__init__.py package initalization
controller/ subpackage
__init__.py subpackage initalization
game_play.py subpackage module
model/ subpackage
__init__.py subpackage initalization
game_play_model.py subpackage module
The __init__.py files can all be empty as they just indicate that the directory is a [sub]package.
For illustrative purposes let's say thegame_play_model.pyfile contained:
print 'hello from game_play_model.py'
and thegame_play.pyfile contains the following to detect when it was being executed directly and adds the name of the parent of its folder — Zimp — to the Python search path — thus allowing you to then directly import other things from the package when it's run that way.
if __name__ == '__main__' and __package__ is None:
import sys, os.path as path
# append parent of the directory the current file is in
sys.path.append(path.dirname(path.dirname(__file__)))
import model.game_play_model
print 'hello from game_play.py'
And you executed it directly with something likepython game_play.pyit would output:
hello from game_play_model.py
hello from game_play.py
4 Comments
if statement and sys.path.append() call have to appear before the import statement.sys.path.append(path.abspath(path.join(path.dirname(__file__), '..'))) which some feel is clearer about what's being done.sys.path.append(path.dirname(path.dirname(__file__))).from Zimp.model import game_play
Should do the trick.
5 Comments
__init__.py file inside the directory. Otherwise it's not recognised as a package/module. Hope that helped.