Search code examples
pythongoogle-app-engineorganization

How to organize code with __init__.py?


I am just starting off using google app engine, and have been looking around for good practices and code organization. Most of my problems lie from confusion of __init__.py.

My current test structure looks like

/website
  main.py
  /pages
    __init__.py #1
    blog.py
    hello2.py
    hello.py
    /sub
      __init__.py #2
      base.py

I am trying to use main.py as a file that simply points to everything in /pages and /pages/sub. Most modules in /pages share almost all the same imports (ex. import urllib), is there a way to define that everything in /pages imports what I want rather than adding it in every individual module?

Currently in __init__.py #1 I have

from sub.base import *

Yet my module blog.py says BaseHandler (a function in base.py) not defined. My end goal is to have something like ...

main.py
from pages import *
#be able to call any function in /pages without having to do blog.func1() or hello.func2()
#rather just func1() and func2()

And to be able to share common imports for modules in /pages in __init__.py. So that they share for example urllib and all functions from base.py. Thank you for taking the time to read this post, I look forward to your insight.


Solution

  • Sounds like you think __init__.py is an initializer for the other modules in the package. It is not. It turns pages into a package (allowing its files and subdirectories to be modules), and it is executed, like a normal module would be, when your program calls import pages. Imagine that it's named pages.py instead.

    So if you really want to dump everything into the same namespace, init #2 can contain from base import * (which will import everything in base to the namespace of sub), and blog.py can contain from sub import *. Got it?