开发者

Import vs C's #include

In C:

#include "foo.h"

int main()
{
}

I believe that "foo.h" effectively gets copied and pasted in at the spot of the "#include".

Python imports are different though, I'm finding.

I just refactored a bit of GAE code that initially had ALL request handlers in one big index.py file.

NEW directory tree:

+
|
+- [handlers]     // all inherit webapp.RequestHandler
+- [models]       // all inherit db.Model
|
+- gl开发者_高级运维obals.py     // contains global variables for site-wide settings
+- index.py       // contains all handler redirects

[handlers] is the folder with the handlers

[models] is the folder with the models

So, index.py goes

from globals import *  # we need all of the globals

# ...

from handlers.FirstPage import FirstPage
from handlers.SecondPage import SecondPage
#.. etc.

SHOULDN'T handlers.FirstPage and handlers.SecondPage "see" everything in globals, since globals is imported "first", before handlers.*?


While in C it works more or less "copy-pasting" the code, in Python is quite different.

Remember the Zen of Python?

Explicit is better than implicit.
...
Namespaces are one honking great idea -- let's do more of those!

Each time you import a module, you execute its code, but you keep all the scopes of the definitions. So, when you import handlers you give index access to the scope of globals, but the handlers module has no access to globals module unless you explicitly allow it to access to the scope, importing it.


yes, they're imported first, but they're imported first into index.py. To be "visible" globals need to be imported in respective files too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜