我应该如何组织 Python 源代码?

我正在开始使用 Python (现在正是我尝试使用它的时候) ,我正在寻找一些最佳实践。

我的第一个项目是一个队列,它在多个线程中运行命令行实验。我开始得到一个非常长的 main.py文件,我想把它分开。一般来说,我在寻找: Python 程序员如何组织多个源文件?是否有一个特定的结构,为您工作?

我的具体问题包括:

  1. 每个类应该放在单独的文件中吗?
  2. 我应该如何组织相对于源代码的单元测试?
  3. 我应该把文档注释放在哪里,特别是那些用于命令行操作的注释?
  4. 如果使用多个目录,如何在它们之间导入类?

在这里,我也许可以通过反复试验得出一些自己的结论,但我宁愿从 很好开始。

41004 次浏览

The way you should organise your code and tests is exactly the same you would for any OO language.

Answers from the way I do it. It may not be right but works for me

  1. Depends on how your functionality is split. For my main python app I have 1 file with classes for the entry points and then packages of different bits of functionality
  2. I use PyDev for eclipse and organise it like I would for Java.
>  Workspace
>     |
>     |-Src
>     |   |-Package1
>     |   |-Package2
>     |   |-main.py
>     |-Test
>         |-TestPackage1
>         |-TestPackage2
  1. Use DocString everywhere to keep track of everything
  2. After making sure that the relevant __init__.py files are in the folders. its just a simple case of from module import class

The article Eric pointed to is awesome because it covers details of organising large Python code bases.

If you've landed here from Google and are trying to find out how to split one large source file into multiple, more manageable, files I'll summarise the process briefly.

Assume you currently have everything in a file called main.py:

  • Create another source file in the same folder (let's call ours utils.py for this example)
  • Move whatever classes, functions, statements, etc you need from main.py into utils.py
  • In main.py add a single line at the top: import utils

Conceptually what this does is to create a new module called utils in another source file. You can then import it wherever it's needed.