让 Python 代码更易维护的七种武器
Python 代码

> 
> 检查你的代码的质量，通过这些外部库使其更易维护。
> 
> 
> 


![](/data/attachment/album/201809/29/104812f8wbi2sbpa2znspa.jpg)



> 
> 可读性很重要。  
>  — <ruby> <a href="https://www.python.org/dev/peps/pep-0020/">  Python 之禅 </a> <rt>  The Zen of Python </rt></ruby>，Tim Peters
> 
> 
> 


随着软件项目进入“维护模式”，对可读性和编码标准的要求很容易落空（甚至从一开始就没有建立过那些标准）。然而，在代码库中保持一致的代码风格和测试标准能够显著减轻维护的压力，也能确保新的开发者能够快速了解项目的情况，同时能更好地全程保持应用程序的质量。


使用外部库来检查代码的质量不失为保护项目未来可维护性的一个好方法。以下会推荐一些我们最喜爱的[检查代码](https://en.wikipedia.org/wiki/Lint_(software))（包括检查 PEP 8 和其它代码风格错误）的库，用它们来强制保持代码风格一致，并确保在项目成熟时有一个可接受的测试覆盖率。


### 检查你的代码风格


[PEP 8](https://www.python.org/dev/peps/pep-0008/) 是 Python 代码风格规范，它规定了类似行长度、缩进、多行表达式、变量命名约定等内容。尽管你的团队自身可能也会有稍微不同于 PEP 8 的代码风格规范，但任何代码风格规范的目标都是在代码库中强制实施一致的标准，使代码的可读性更强、更易于维护。下面三个库就可以用来帮助你美化代码。


#### 1、 Pylint


[Pylint](https://www.pylint.org/) 是一个检查违反 PEP 8 规范和常见错误的库。它在一些流行的[编辑器和 IDE](https://pylint.readthedocs.io/en/latest/user_guide/ide-integration.html) 中都有集成，也可以单独从命令行运行。


执行 `pip install pylint` 安装 Pylint 。然后运行 `pylint [options] path/to/dir` 或者 `pylint [options] path/to/module.py` 就可以在命令行中使用 Pylint，它会向控制台输出代码中违反规范和出现错误的地方。


你还可以使用 `pylintrc` [配置文件](https://pylint.readthedocs.io/en/latest/user_guide/run.html#command-line-options)来自定义 Pylint 对哪些代码错误进行检查。


#### 2、 Flake8


[Flake8](http://flake8.pycqa.org/en/latest/) 是“将 PEP 8、Pyflakes（类似 Pylint）、McCabe（代码复杂性检查器）和第三方插件整合到一起，以检查 Python 代码风格和质量的一个 Python 工具”。


执行 `pip install flake8` 安装 flake8 ，然后执行 `flake8 [options] path/to/dir` 或者 `flake8 [options] path/to/module.py` 可以查看报出的错误和警告。


和 Pylint 类似，Flake8 允许通过[配置文件](http://flake8.pycqa.org/en/latest/user/configuration.html#configuration-locations)来自定义检查的内容。它有非常清晰的文档，包括一些有用的[提交钩子](http://flake8.pycqa.org/en/latest/user/using-hooks.html)，可以将自动检查代码纳入到开发工作流程之中。


Flake8 也可以集成到一些流行的编辑器和 IDE 当中，但在文档中并没有详细说明。要将 Flake8 集成到喜欢的编辑器或 IDE 中，可以搜索插件（例如 [Sublime Text 的 Flake8 插件](https://github.com/SublimeLinter/SublimeLinter-flake8)）。


#### 3、 Isort


[Isort](https://github.com/timothycrosley/isort) 这个库能将你在项目中导入的库按字母顺序排序，并将其[正确划分为不同部分](https://github.com/timothycrosley/isort#how-does-isort-work)（例如标准库、第三方库、自建的库等）。这样提高了代码的可读性，并且可以在导入的库较多的时候轻松找到各个库。


执行 `pip install isort` 安装 isort，然后执行 `isort path/to/module.py` 就可以运行了。[文档](https://github.com/timothycrosley/isort#using-isort)中还提供了更多的配置项，例如通过[配置](https://github.com/timothycrosley/isort#configuring-isort) `.isort.cfg` 文件来决定 isort 如何处理一个库的多行导入。


和 Flake8、Pylint 一样，isort 也提供了将其与流行的[编辑器和 IDE](https://github.com/timothycrosley/isort/wiki/isort-Plugins) 集成的插件。


### 分享你的代码风格


每次文件发生变动之后都用命令行手动检查代码是一件痛苦的事，你可能也不太喜欢通过运行 IDE 中某个插件来实现这个功能。同样地，你的同事可能会用不同的代码检查方式，也许他们的编辑器中也没有那种插件，甚至你自己可能也不会严格检查代码和按照警告来更正代码。总之，你分享出来的代码库将会逐渐地变得混乱且难以阅读。


一个很好的解决方案是使用一个库，自动将代码按照 PEP 8 规范进行格式化。我们推荐的三个库都有不同的自定义级别来控制如何格式化代码。其中有一些设置较为特殊，例如 Pylint 和 Flake8 ，你需要先行测试，看看是否有你无法忍受但又不能修改的默认配置。


#### 4、 Autopep8


[Autopep8](https://github.com/hhatto/autopep8) 可以自动格式化指定的模块中的代码，包括重新缩进行、修复缩进、删除多余的空格，并重构常见的比较错误（例如布尔值和 `None` 值）。你可以查看文档中完整的[更正列表](https://github.com/hhatto/autopep8#id4)。


运行 `pip install --upgrade autopep8` 安装 Autopep8。然后执行 `autopep8 --in-place --aggressive --aggressive <filename>` 就可以重新格式化你的代码。`aggressive` 选项的数量表示 Auotopep8 在代码风格控制上有多少控制权。在这里可以详细了解 [aggressive](https://github.com/hhatto/autopep8#id5) 选项。


#### 5、 Yapf


[Yapf](https://github.com/google/yapf) 是另一种有自己的[配置项](https://github.com/google/yapf#usage)列表的重新格式化代码的工具。它与 Autopep8 的不同之处在于它不仅会指出代码中违反 PEP 8 规范的地方，还会对没有违反 PEP 8 但代码风格不一致的地方重新格式化，旨在令代码的可读性更强。


执行 `pip install yapf` 安装 Yapf，然后执行 `yapf [options] path/to/dir` 或 `yapf [options] path/to/module.py` 可以对代码重新格式化。[定制选项](https://github.com/google/yapf#usage)的完整列表在这里。


#### 6、 Black


[Black](https://github.com/ambv/black) 在代码检查工具当中算是比较新的一个。它与 Autopep8 和 Yapf 类似，但限制较多，没有太多的自定义选项。这样的好处是你不需要去决定使用怎么样的代码风格，让 Black 来给你做决定就好。你可以在这里查阅 Black [有限的自定义选项](https://github.com/ambv/black#command-line-options)以及[如何在配置文件中对其进行设置](https://github.com/ambv/black#pyprojecttoml)。


Black 依赖于 Python 3.6+，但它可以格式化用 Python 2 编写的代码。执行 `pip install black` 安装 Black，然后执行 `black path/to/dir` 或 `black path/to/module.py` 就可以使用 Black 优化你的代码。


### 检查你的测试覆盖率


如果你正在进行编写测试，你需要确保提交到代码库的新代码都已经测试通过，并且不会降低测试覆盖率。虽然测试覆盖率不是衡量测试有效性和充分性的唯一指标，但它是确保项目遵循基本测试标准的一种方法。对于计算测试覆盖率，我们推荐使用 Coverage 这个库。


#### 7、 Coverage


[Coverage](https://coverage.readthedocs.io/en/latest/) 有数种显示测试覆盖率的方式，包括将结果输出到控制台或 HTML 页面，并指出哪些具体哪些地方没有被覆盖到。你可以通过[配置文件](https://coverage.readthedocs.io/en/latest/config.html)自定义 Coverage 检查的内容，让你更方便使用。


执行 `pip install coverage` 安装 Converage 。然后执行 `coverage [path/to/module.py] [args]` 可以运行程序并查看输出结果。如果要查看哪些代码行没有被覆盖，执行 `coverage report -m` 即可。


### 持续集成工具


<ruby> 持续集成 <rt>  Continuous integration </rt></ruby>（CI）是在合并和部署代码之前自动检查代码风格错误和测试覆盖率最小值的过程。很多免费或付费的工具都可以用于执行这项工作，具体的过程不在本文中赘述，但 CI 过程是令代码更易读和更易维护的重要步骤，关于这一部分可以参考 [Travis CI](https://travis-ci.org/) 和 [Jenkins](https://jenkins.io/)。


以上这些只是用于检查 Python 代码的各种工具中的其中几个。如果你有其它喜爱的工具，欢迎在评论中分享。




---


via: <https://opensource.com/article/18/7/7-python-libraries-more-maintainable-code>


作者：[Jeff Triplett](https://opensource.com/users/laceynwilliams) 选题：[lujun9972](https://github.com/lujun9972) 译者：[HankChow](https://github.com/HankChow) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
Readability counts.


—[The Zen of Python], Tim Peters

It's easy to let readability and coding standards fall by the wayside when a software project moves into "maintenance mode." (It's also easy to never establish those standards in the first place.) But maintaining consistent style and testing standards across a codebase is an important part of decreasing the maintenance burden, ensuring that future developers are able to quickly grok what's happening in a new-to-them project and safeguarding the health of the app over time.


A great way to protect the future maintainability of a project is to use external libraries to check your code health for you. These are a few of our favorite libraries for [linting code](https://en.wikipedia.org/wiki/Lint_(software)) (checking for PEP 8 and other style errors), enforcing a consistent style, and ensuring acceptable test coverage as a project reaches maturity.

## Check your code style

[PEP 8](https://www.python.org/dev/peps/pep-0008/) is the Python code style guide, and it sets out rules for things like line length, indentation, multi-line expressions, and naming conventions. Your team might also have your own style rules that differ slightly from PEP 8. The goal of any code style guide is to enforce consistent standards across a codebase to make it more readable, and thus more maintainable. Here are three libraries to help prettify your code.

### 1. Pylint

[Pylint](https://www.pylint.org/) is a library that checks for PEP 8 style violations and common errors. It integrates well with several popular [editors and IDEs](https://pylint.readthedocs.io/en/latest/user_guide/ide-integration.html) and can also be run from the command line.

To install, run `pip install pylint`

.

To use Pylint from the command line, run `pylint [options] path/to/dir`

or `pylint [options] path/to/module.py`

. Pylint will output warnings about style violations and other errors to the console.

You can customize what errors Pylint checks for with a [configuration file](https://pylint.readthedocs.io/en/latest/user_guide/run.html#command-line-options) called `pylintrc`

.

### 2. Flake8

[Flake8](http://flake8.pycqa.org/en/latest/) is a "Python tool that glues together PEP8, Pyflakes (similar to Pylint), McCabe (code complexity checker), and third-party plugins to check the style and quality of some Python code."

To use Flake8, run `pip install flake8`

. Then run `flake8 [options] path/to/dir`

or `flake8 [options] path/to/module.py`

to see its errors and warnings.

Like Pylint, Flake8 permits some customization for what it checks for with a [configuration file](http://flake8.pycqa.org/en/latest/user/configuration.html#configuration-locations). It has very clear docs, including some on useful [commit hooks](http://flake8.pycqa.org/en/latest/user/using-hooks.html) to automatically check your code as part of your development workflow.

Flake8 integrates with popular editors and IDEs, but those instructions generally aren't found in the docs. To integrate Flake8 with your favorite editor or IDE, search online for plugins (for example, [Flake8 plugin for Sublime Text](https://github.com/SublimeLinter/SublimeLinter-flake8)).

### 3. Isort

[Isort](https://github.com/timothycrosley/isort) is a library that sorts your imports alphabetically and breaks them up into [appropriate sections](https://github.com/timothycrosley/isort#how-does-isort-work) (e.g., standard library imports, third-party library imports, imports from your own project, etc.). This increases readability and makes it easier to locate imports if you have a lot of them in your module.

Install isort with `pip install isort`

, and run it with `isort path/to/module.py`

. More configuration options are in the [documentation](https://github.com/timothycrosley/isort#using-isort). For example, you can [configure](https://github.com/timothycrosley/isort#configuring-isort) how isort handles multi-line imports from one library in an `.isort.cfg`

file.

Like Flake8 and Pylint, isort also provides plugins that integrate it with popular [editors and IDEs](https://github.com/timothycrosley/isort/wiki/isort-Plugins).

## Outsource your code style

Remembering to run linters manually from the command line for each file you change is a pain, and you might not like how a particular plugin behaves with your IDE. Also, your colleagues might prefer different linters or might not have plugins for their favorite editors, or you might be less meticulous about always running the linter and correcting the warnings. Over time, the codebase you all share will get messy and harder to read.

A great solution is to use a library that automatically reformats your code into something that passes PEP 8 for you. The three libraries we recommend all have different levels of customization and different defaults for how they format code. Some of these are more opinionated than others, so like with Pylint and Flake8, you'll want to test these out to see which offers the customizations you can't live without… and the unchangeable defaults you can live *with*.

### 4. Autopep8

[Autopep8](https://github.com/hhatto/autopep8) automatically formats the code in the module you specify. It will re-indent lines, fix indentation, remove extraneous whitespace, and refactor common comparison mistakes (like with booleans and `None`

). See a full [list of corrections](https://github.com/hhatto/autopep8#id4) in the docs.

To install, run `pip install --upgrade autopep8`

. To reformat code in place, run `autopep8 --in-place --aggressive --aggressive <filename>`

. The `aggressive`

flags (and the number of them) indicate how much control you want to give autopep8 over your code style. Read more about [aggressive](https://github.com/hhatto/autopep8#id5) options.

### 5. Yapf

[Yapf](https://github.com/google/yapf) is yet another option for reformatting code that comes with its own list of [configuration options](https://github.com/google/yapf#usage). It differs from autopep8 in that it doesn't just address PEP 8 violations. It also reformats code that doesn't violate PEP 8 specifically but isn't styled consistently or could be formatted better for readability.

To install, run `pip install yapf`

. To reformat code, run, `yapf [options] path/to/dir`

or `yapf [options] path/to/module.py`

. There is also a full list of [customization options](https://github.com/google/yapf#usage).

### 6. Black

[Black](https://github.com/ambv/black) is the new kid on the block for linters that reformat code in place. It's similar to autopep8 and Yapf, but way more opinionated. It has very few options for customization, which is kind of the point. The idea is that you shouldn't have to make decisions about code style; the only decision to make is to let Black decide for you. You can read about [limited customization options](https://github.com/ambv/black#command-line-options) and instructions on [storing them in a configuration file](https://github.com/ambv/black#pyprojecttoml).

Black requires Python 3.6+ but can format Python 2 code. To use, run `pip install black`

. To prettify your code, run: `black path/to/dir`

or `black path/to/module.py`

.

## Check your test coverage

You're writing tests, right? Then you will want to make sure new code committed to your codebase is tested and doesn't drop your overall amount of test coverage. While percentage of test coverage is not the only metric you should use to measure the effectiveness and sufficiency of your tests, it is one way to ensure basic testing standards are being followed in your project. For measuring test coverage, we have one recommendation: Coverage.

### 7. Coverage

[Coverage](https://coverage.readthedocs.io/en/latest/) has several options for the way it reports your test coverage to you, including outputting results to the console or to an HTML page and indicating which line numbers are missing test coverage. You can set up a [configuration file](https://coverage.readthedocs.io/en/latest/config.html) to customize what Coverage checks for and make it easier to run.

To install, run `pip install coverage`

. To run a program and see its output, run `coverage run [path/to/module.py] [args]`

, and you will see your program's output. To see a report of which lines of code are missing coverage, run `coverage report -m`

.

## Continuous integration tools

Continuous integration (CI) is a series of processes you can run to automatically check for linter errors and test coverage minimums before you merge and deploy code. There are lots of free or paid tools to automate this process, and a thorough walkthrough is beyond the scope of this article. But because setting up a CI process is an important step in removing blocks to more readable and maintainable code, you should investigate continuous integration tools in general; check out [Travis CI](https://travis-ci.org/) and [Jenkins](https://jenkins.io/) in particular.

These are only a handful of the libraries available to check your Python code. If you have a favorite that's not on this list, please share it in the comments.

## 2 Comments