Reputation: 9701
I am writing a game framework. Here is my current file structure:
src/
framework/
__init__.py
util.py
render.py
game.py
pong.py
I want to be able to simply do import game
or import render
directly from the pong.py
file. What's the best way to accomplish this? Initially the util.py, render.py, game.py
modules were in the src
folder but I decided to put them into their separate folder for the sake of organization. I am quite new at packaging conventions so I don't know if this would be the recommended way of doing things.
Upvotes: 4
Views: 455
Reputation: 229281
The best way to do this would be not to do it at all. For exactly the reasons you moved them in the first place - the sake of organization - you'll want them to be in a separate module. If you want to refer to the module as game
in your code, you can do this:
from framework import game
game.foo()
Generally, when you do import game
, you are providing the expectation that game
is either a system library or in the folder the script is running at. If that isn't the case, it will throw people off. If you were to make your framework a system library, you wouldn't have it as three separate libraries util
, game
, and render
, no? You'd package it in one library - framework
- and distribute that, with submodules. Thus you're really not going to want to do this.
But, as I know non-answers can be frustrating, if you really want to go ahead you can add the framework
folder to sys.path
, which python checks whenever you import a module:
import sys
sys.path.append("framework")
import game
Upvotes: 7