4

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.

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

2 Comments

Would from framework import * work? I know it's not recommended but I was reading some stuff about the __all__ variable that can be defined in __init__.py so I'm not sure.
@Lanaru: try this: in your __init__.py, put in import game; import render; import util;, and i think then import * will work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.