我应该如何组织 Python 源代码? [英] How should I organize Python source code?

查看:27
本文介绍了我应该如何组织 Python 源代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm getting started with Python (it's high time I give it a shot), and I'm looking for some best practices.

我的第一个项目是在多个线程中运行命令行实验的队列.我开始得到一个很长的 main.py 文件,我想把它拆开.一般而言,我在寻找:python 程序员如何组织多个源文件?是否有适合您的特定结构?

My first project is a queue which runs command-line experiments in multiple threads. I'm starting to get a very long main.py file, and I'd like to break it up. In general, I'm looking for: How do python programmers organize multiple source files? Is there a particular structure that works for you?

我的具体问题包括:

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

我可能可以通过反复试验得出一些我自己的结论,但我宁愿从一些好的开始.

I can probably draw some of my own conclusions here by trial and error, but I'd rather start from something good.

推荐答案

Eric 指出的文章很棒,因为它涵盖了组织大型 Python 代码库的详细信息.

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

如果您是从 Google 来到这里的,并且正在尝试找出如何将一个大型源文件拆分为多个更易于管理的文件,我将简要总结一下该过程.

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.

假设您目前在名为 main.py 的文件中拥有所有内容:

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

  • 在同一个文件夹中创建另一个源文件(在这个例子中我们称之为 utils.py)
  • 将您需要的任何类、函数、语句等从 main.py 移动到 utils.py
  • main.py顶部添加一行:import utils
  • 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

从概念上讲,这是在另一个源文件中创建一个名为 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.

这篇关于我应该如何组织 Python 源代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆