How to organize code with __init__.py?

I'm just starting to use the Google engine for advertising and have been looking for good practice and code organization. Most of my problems are related to the __init__.py confusion.

My current testing framework 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 just points to everything in / pages and / pages / sub. Most modules in / pages have almost all the same imports (e.g. import urllib), is there a way to determine that everything in / pages imports what I want, rather than adding it to each individual module?

Currently in __init__.py # 1 I have

 from sub.base import * 

However, my blog.py module says that BaseHandler (a function in base.py) is not defined. My ultimate 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 a common import for modules in /pages in __init__.py . So that they share, for example, urllib and all functions with base.py. Thank you for taking the time to read this post, I look forward to your understanding.

+4
source share
1 answer

It sounds like you think __init__.py is the initializer for the other modules in the package. Is not. It turns pages into a package (allowing its files and subdirectories to be modules), and it runs like a regular module when your program calls import pages . Imagine that it was named pages.py .

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

+3
source

All Articles