How to set up Python packages
Question: 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


Answer: 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_](http://stackoverflow.com/questions/11536764/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 the`game_play_model.py`file contained:

    
    
    print 'hello from game_play_model.py'
    

and the`game_play.py`file 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 like`python game_play.py`it would
output:

    
    
    hello from game_play_model.py
    hello from game_play.py
    

