开发者

python module layout

I'm just starting to get to the point in my python projects that I need to st开发者_StackOverflow中文版art using multiple packages and I'm a little confused on exactly how everything is supposed to work together. What exactly should go into the __init__.py of the package? Some projects I see just have blank inits and all of their code are in modules in that package. Other projects implement what seems to be the majority of the package's classes and functions inside the init.

Is there a document or style guide or something that describes what the python authors had in mind for the use of packages and the __init__ file and such?

Edit:

I know the point of having the __init__.py file in the simplest sense that it makes a folder a package. But why would I put a function there instead of a module in that same folder(package)?


__init__.py can be empty, but what it really does is make sure Python treats your directories correctly, provide any initialization you might need for when your package is imported (configuring the environment or something along those lines), or defining __all__ so that Python knows what to do when someone uses from package import *.

Most everything you need to know is described in the docs on Packages. Dive Into Python also has a piece on packaging.


You already know, I guess that __init__.py files are required to make Python treat the directories as containing packages.

  1. In the above model __init__.py can remain empty.

  2. You can can also execute initialization code for the package.

  3. You can also set the __all__ variable.

[Edit: learnings] When you do "from package import item", or "from package import *", then the variable __all__ can be used to import selected packages.

See : http://docs.python.org/tutorial/modules.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜