Python代码质量:工具和最佳实践

In this article, we’ll identify high-quality Python code and show you how to improve the quality of your own code.

在本文中,我们将识别高质量的Python代码,并向您展示如何提高自己的代码质量。

We’ll analyze and compare tools you can use to take your code to the next level. Whether you’ve been using Python for a while, or just beginning, you can benefit from the practices and tools talked about here.

我们将分析和比较可用于将代码提升到新水平的工具。 无论您是长期使用Python还是刚开始使用Python,都可以从这里讨论的实践和工具中受益。

什么是代码质量? (What is Code Quality?)

Of course you want quality code, who wouldn’t? But to improve code quality, we have to define what it is.

当然,您需要质量代码,谁不会呢? 但是为了提高代码质量,我们必须定义它的含义。

A quick Google search yields many results defining code quality. As it turns out, the term can mean many different things to people.

快速的Google搜索会产生许多定义代码质量的结果。 事实证明,该术语对人们可能意味着许多不同的东西。

One way of trying to define code quality is to look at one end of the spectrum: high-quality code. Hopefully, you can agree on the following high-quality code identifiers:

尝试定义代码质量的一种方法是查看频谱的一端:高质量代码。 希望您可以同意以下高质量代码标识符:

  • It does what it is supposed to do.
  • It does not contain defects or problems.
  • It is easy to read, maintain, and extend.
  • 它完成了应该做的事情。
  • 它不包含缺陷或问题。
  • 它易于阅读,维护和扩展。

These three identifiers, while simplistic, seem to be generally agreed upon. In an effort to expand these ideas further, let’s delve into why each one matters in the realm of software.

这三个标识符虽然很简单,但似乎已被普遍认可。 为了进一步扩展这些想法,让我们深入研究为什么每个问题在软件领域都很重要。

为什么代码质量很重要? (Why Does Code Quality Matter?)

To determine why high-quality code is important, let’s revisit those identifiers. We’ll see what happens when code doesn’t meet them.

为了确定高质量代码为何如此重要,让我们重新访问这些标识符。 我们将看到代码不符合要求时会发生什么。

没有做应该做的事 (It does not do what it is supposed to do)

Meeting requirements is the basis of any product, software or otherwise. We make software to do something. If in the end, it doesn’t do it… well it’s definitely not high quality. If it doesn’t meet basic requirements, it’s hard to even call it low quality.

满足要求是任何产品,软件或其他产品的基础。 我们制作软件来做某事。 如果最后还是没有做到……那绝对不是高质量。 如果不满足基本要求,就很难称其为低质量。

确实包含缺陷和问题 (It does contain defects and problems)

If something you’re using has issues or causes you problems, you probably wouldn’t call it high-quality. In fact, if it’s bad enough, you may stop using it altogether.

如果您使用的东西有问题或导致问题,您可能不会称其为高质量。 实际上,如果它足够糟糕,您可能会完全停止使用它。

For the sake of not using software as an example, let’s say your vacuum works great on regular carpet. It cleans up all the dust and cat hair. One fateful night the cat knocks over a plant, spilling dirt everywhere. When you try to use the vacuum to clean the pile of dirt, it breaks, spewing the dirt everywhere.

为了不使用软件作为示例,假设您的吸尘器在普通地毯上效果很好。 它可以清除所有灰尘和猫毛。 命运的一个夜晚,猫把植物撞倒,到处都是泥土。 当您尝试使用真空吸尘器清洁一堆污垢时,它会破裂,将污垢喷到各处。

While the vacuum worked under some circumstances, it didn’t efficiently handle the occasional extra load. Thus, you wouldn’t call it a high-quality vacuum cleaner.

尽管真空在某些情况下仍然有效,但它并不能有效地处理偶尔的额外负载。 因此,您不会称其为高质量的真空吸尘器。

That is a problem we want to avoid in our code. If things break on edge cases and defects cause unwanted behavior, we don’t have a high-quality product.

我们要在代码中避免这个问题。 如果情况突然恶化并且缺陷导致不良行为,我们将没有高质量的产品。

难以阅读,维护或扩展 (It is difficult to read, maintain, or extend)

Imagine this: a customer requests a new feature. The person who wrote the original code is gone. The person who has replaced them now has to make sense of the code that’s already there. That person is you.

想象一下:客户请求一项新功能。 编写原始代码的人不见了。 现在,替换它们的人必须了解已经存在的代码。 那个人就是你

If the code is easy to comprehend, you’ll be able to analyze the problem and come up with a solution much quicker. If the code is complex and convoluted, you’ll probably take longer and possibly make some wrong assumptions.

如果代码易于理解,您将能够分析问题并更快地提出解决方案。 如果代码复杂且令人费解,则可能需要花费更长的时间,并可能做出一些错误的假设。

It’s also nice if it’s easy to add the new feature without disrupting previous features. If the code is not easy to extend, your new feature could break other things.

如果很容易添加新功能而又不破坏以前的功能,那也很好。 如果代码不容易扩展,那么您的新功能可能会破坏其他功能。

No one wants to be in the position where they have to read, maintain, or extend low-quality code. It means more headaches and more work for everyone.

没有人愿意站在必须阅读,维护或扩展低质量代码的位置。 这意味着每个人都有更多的头痛和更多的工作。

It’s bad enough that you have to deal with low-quality code, but don’t put someone else in the same situation. You can improve the quality of code that you write.

您必须处理低质量的代码,但又不要让其他人处于同样的境地,这已经很糟糕了。 您可以提高所编写代码的质量。

If you work with a team of developers, you can start putting into place methods to ensure better overall code quality. Assuming that you have their support, of course. You may have to win some people over (feel free to send them this article 😃).

如果与开发人员团队合作,则可以开始采用适当的方法来确保更好的整体代码质量。 当然,假设您有他们的支持。 您可能需要赢得一些人的支持(请随时向他们发送本文😃)。

如何提高Python代码质量 (How to Improve Python Code Quality)

There are a few things to consider on our journey for high-quality code. First, this journey is not one of pure objectivity. There are some strong feelings of what high-quality code looks like.

在使用高质量代码的过程中,需要考虑一些事项。 首先,这一旅程不是纯粹的客观性之一。 对高质量代码的外观有一些强烈的感觉。

While everyone can hopefully agree on the identifiers mentioned above, the way they get achieved is a subjective road. The most opinionated topics usually come up when you talk about achieving readability, maintenance, and extensibility.

尽管每个人都可以希望就上述标识符达成共识,但是实现它们的方法是主观的。 当您谈论实现可读性,维护性和可扩展性时,最自以为是的话题通常会出现。

So keep in mind that while this article will try to stay objective throughout, there is a very-opinionated world out there when it comes to code.

因此,请记住,尽管本文将始终保持客观性,但在代码方面还是有一个很好的建议。

So, let’s start with the most opinionated topic: code style.

因此,让我们从最自以为是的主题开始:代码样式。

风格指南 (Style Guides)

Ah, yes. The age-old question: spaces or tabs?

是的。 古老的问题: 空格或制表符

Regardless of your personal view on how to represent whitespace, it’s safe to assume that you at least want consistency in code.

无论您对如何表示空白有什么个人看法,都可以安全地假设您至少想要代码的一致性。

A style guide serves the purpose of defining a consistent way to write your code. Typically this is all cosmetic, meaning it doesn’t change the logical outcome of the code. Although, some stylistic choices do avoid common logical mistakes.

样式指南的目的是定义一致的代码编写方式。 通常,这些都是修饰性的,这意味着它不会改变代码的逻辑结果。 虽然,某些样式选择确实避免了常见的逻辑错误。

Style guides serve to help facilitate the goal of making code easy to read, maintain, and extend.

样式指南有助于实现使代码易于阅读,维护和扩展的目标。

As far as Python goes, there is a well-accepted standard. It was written, in part, by the author of the Python programming language itself.

就Python而言,有一个公认的标准。 它部分是由Python编程语言本身的作者编写的。

PEP 8 provides coding conventions for Python code. It is fairly common for Python code to follow this style guide. It’s a great place to start since it’s already well-defined.

PEP 8提供了Python代码的编码约定。 Python代码遵循此样式指南非常普遍。 这是一个很好的起点,因为它已经明确定义。

A sister Python Enhancement Proposal, PEP 257 describes conventions for Python’s docstrings, which are strings intended to document modules, classes, functions, and methods. As an added bonus, if docstrings are consistent, there are tools capable of generating documentation directly from the code.

PEP 257是一个姊妹的Python增强建议,描述了Python文档字符串的约定,这些文档字符串旨在记录模块,类,函数和方法。 另外,如果文档字符串一致,则有一些工具可以直接从代码生成文档。

All these guides do is define a way to style code. But how do you enforce it? And what about defects and problems in the code, how can you detect those? That’s where linters come in.

这些指南的全部作用就是定义一种样式代码。 但是您如何执行呢? 那么代码中的缺陷和问题又如何呢? 这就是短毛绒的来历。

短绒 (Linters)

什么是短绒棉? (What is a Linter?)

First, let’s talk about lint. Those tiny, annoying little defects that somehow get all over your clothes. Clothes look and feel much better without all that lint. Your code is no different. Little mistakes, stylistic inconsistencies, and dangerous logic don’t make your code feel great.

首先,让我们谈谈皮棉。 那些微小的,令人讨厌的小缺陷以某种方式遍布您的衣服。 衣服看起来和感觉都好很多,没有掉毛。 您的代码没什么不同。 小错误,风格不一致和危险的逻辑不会使您的代码感觉良好。

But we all make mistakes. You can’t expect yourself to always catch them in time. Mistyped variable names, forgetting a closing bracket, incorrect tabbing in Python, calling a function with the wrong number of arguments, the list goes on and on. Linters help to identify those problem areas.

但是我们都会犯错。 您不能期望自己总是能及时赶上他们。 变量名输入错误,忘记了右括号,在Python中使用不正确的制表键,使用错误数量的参数调用函数,该列表将不胜枚举。 短绒帮助确定那些问题区域。

Additionally, most editors and IDE’s have the ability to run linters in the background as you type. This results in an environment capable of highlighting, underlining, or otherwise identifying problem areas in the code before you run it. It is like an advanced spell-check for code. It underlines issues in squiggly red lines much like your favorite word processor does.

此外,大多数编辑器和IDE都可以在您键入内容时在后台运行Linters。 这将导致环境能够在运行代码之前突出显示,加下划线或以其他方式标识代码中的问题区域。 就像是高级的拼写检查代码。 就像您最喜欢的文字处理器一样,它会以红色波浪线突出显示问题。

Linters analyze code to detect various categories of lint. Those categories can be broadly defined as the following:

短绒分析代码以检测各种类别的短绒。 这些类别可以大致定义如下:

  1. Logical Lint
    • Code errors
    • Code with potentially unintended results
    • Dangerous code patterns
  2. Stylistic Lint
    • Code not conforming to defined conventions
  1. 逻辑皮棉
    • 代码错误
    • 可能产生意外结果的代码
    • 危险代码模式
  2. 文体皮棉
    • 代码不符合定义的约定

There are also code analysis tools that provide other insights into your code. While maybe not linters by definition, these tools are usually used side-by-side with linters. They too hope to improve the quality of the code.

还有一些代码分析工具可为您的代码提供其他见解。 虽然从定义上讲可能不是短绒,但这些工具通常与短绒并排使用。 他们也希望提高代码的质量。

Finally, there are tools that automatically format code to some specification. These automated tools ensure that our inferior human minds don’t mess up conventions.

最后,有些工具会自动将代码格式化为某些规范。 这些自动化工具确保我们下等的人不会弄乱惯例。

我的Python Linter选项有哪些? (What Are My Linter Options For Python?)

Before delving into your options, it’s important to recognize that some “linters” are just multiple linters packaged nicely together. Some popular examples of those combo-linters are the following:

在研究您的选择之前,重要的是要认识到,某些“棉绒”只是好好包装在一起的多个棉绒。 以下是这些组合垫的一些流行示例:

Flake8: Capable of detecting both logical and stylistic lint. It adds the style and complexity checks of pycodestyle to the logical lint detection of PyFlakes. It combines the following linters:

Flake8 :能够检测逻辑和样式棉绒。 它将pycodestyle的样式和复杂性检查添加到PyFlakes的逻辑皮棉检测中。 它结合了以下短毛绒:

  • PyFlakes
  • pycodestyle (formerly pep8)
  • Mccabe
  • PyFlakes
  • pycodestyle(以前为pep8)
  • 麦卡比

Pylama: A code audit tool composed of a large number of linters and other tools for analyzing code. It combines the following:

Pylama :一种代码审核工具,由大量短绒和其他用于分析代码的工具组成。 它结合了以下内容:

  • pycodestyle (formerly pep8)
  • pydocstyle (formerly pep257)
  • PyFlakes
  • Mccabe
  • Pylint
  • Radon
  • gjslint
  • pycodestyle(以前为pep8)
  • pydocstyle(以前是pep257)
  • PyFlakes
  • 麦卡比
  • 皮林特
  • gjslint

Here are some stand-alone linters categorized with brief descriptions:

以下是一些带有简要说明的独立棉短绒:

Linter 林特 Category 类别 Description 描述
Pylint皮林特 Logical & Stylistic 逻辑和文体 Checks for errors, tries to enforce a coding standard, looks for code smells 检查错误,尝试执行编码标准,查找代码气味
PyFlakesPyFlakes Logical 逻辑上 Analyzes programs and detects various errors 分析程序并检测各种错误
pycodestylepycodestyle Stylistic 文体 Checks against some of the style conventions in PEP 8 检查PEP 8中的某些样式约定
pydocstylepydocstyle Stylistic 文体 Checks compliance with Python docstring conventions 检查是否符合Python文档字符串约定
Bandit土匪 Logical 逻辑上 Analyzes code to find common security issues 分析代码以查找常见的安全问题
MyPyMyPy Logical 逻辑上 Checks for optionally-enforced static types 检查强制执行的静态类型

And here are some code analysis and formatting tools:

这里是一些代码分析和格式化工具:

Tool 工具 Category 类别 Description 描述
Mccabe麦卡比 Analytical 分析型 McCabe complexityMcCabe的复杂性
Radon Analytical 分析型 Analyzes code for various metrics (lines of code, complexity, and so on) 分析各种指标的代码(代码行,复杂度等)
Black黑色 Formatter 格式化程序 Formats Python code without compromise 毫不妥协地格式化Python代码
IsortIsort Formatter 格式化程序 Formats imports by sorting alphabetically and separating into sections 通过按字母顺序排序并分成几部分来格式化导入

比较Python Linter (Comparing Python Linters)

Let’s get a better idea of what different linters are capable of catching and what the output looks like. To do this, I ran the same code through a handful of different linters with the default settings.

让我们更好地了解哪些不同的短绒棉能够捕获,输出看起来如何。 为此,我使用少数几个默认设置运行了相同的代码。

The code I ran through the linters is below. It contains various logical and stylistic issues:

我在短绒棉布上跑过的代码如下。 它包含各种逻辑和样式问题:

 """
"""
code_with_lint.py
code_with_lint.py
Example Code with lots of lint!
Example Code with lots of lint!
"""
"""
import import io
io
from from math math import import *


*


from from time time import import time

time

some_global_var some_global_var = = 'GLOBAL VAR NAMES SHOULD BE IN ALL_CAPS_WITH_UNDERSCOES'

'GLOBAL VAR NAMES SHOULD BE IN ALL_CAPS_WITH_UNDERSCOES'

def def multiplymultiply (( xx , , yy ):
    ):
    """
"""
    This returns the result of a multiplation of the inputs
    This returns the result of a multiplation of the inputs
    """
        """
    some_global_var some_global_var = = 'this is actually a local variable...'
    'this is actually a local variable...'
    result result = = xx * * y
    y
    return return result
    result
    if if result result == == 777777 :
        :
        printprint (( "jackpot!""jackpot!" )

)

def def is_sum_luckyis_sum_lucky (( xx , , yy ):
    ):
    """This returns a string describing whether or not the sum of input is lucky
"""This returns a string describing whether or not the sum of input is lucky
    This function first makes sure the inputs are valid and then calculates the
    This function first makes sure the inputs are valid and then calculates the
    sum. Then, it will determine a message to return based on whether or not
    sum. Then, it will determine a message to return based on whether or not
    that sum should be considered "lucky"
    that sum should be considered "lucky"
    """
        """
    if if x x != != NoneNone :
        :
        if if y y is is not not NoneNone :
            :
            result result = = xx ++ yy ;
            ;
            if if result result == == 77 :
                :
                return return 'a lucky number!'
            'a lucky number!'
            elseelse :
                :
                returnreturn ( ( 'an unlucky number!''an unlucky number!' )

            )

            return return (( 'just a normal number''just a normal number' )

)

class class SomeClassSomeClass :

    :

    def def __init____init__ (( selfself , , some_argsome_arg ,  ,  some_other_argsome_other_arg , , verbose verbose = = FalseFalse ):
        ):
        selfself .. some_other_arg  some_other_arg  =  =  some_other_arg
        some_other_arg
        selfself .. some_arg        some_arg        =  =  some_arg
        some_arg
        list_comprehension list_comprehension = = [(([(( 100100 // valuevalue )) ** pipi ) ) for for value value in in some_arg some_arg if if value value != != 00 ]
        ]
        time time = = timetime ()
        ()
        from from datetime datetime import import datetime
        datetime
        date_and_time date_and_time = = datetimedatetime .. nownow ()
        ()
        return
return

The comparison below shows the linters I used and their runtime for analyzing the above file. I should point out that these aren’t all entirely comparable as they serve different purposes. PyFlakes, for example, does not identify stylistic errors like Pylint does.

下面的比较显示了我用于分析上述文件的短毛绒及其运行时间。 我应该指出,由于它们具有不同的用途,因此并非全部具有可比性。 例如,PyFlakes不能像Pylint一样识别样式错误。

Linter 林特 Command 命令 Time 时间
Pylint皮林特 pylint code_with_lint.py pylint code_with_lint.py 1.16s 1.16秒
PyFlakesPyFlakes pyflakes code_with_lint.py pyflakes code_with_lint.py 0.15s 0.15秒
pycodestylepycodestyle pycodestyle code_with_lint.py pycodestyle code_with_lint.py 0.14s 0.14秒
pydocstylepydocstyle pydocstyle code_with_lint.py pydocstyle code_with_lint.py 0.21s 0.21秒

For the outputs of each, see the sections below.

有关每个输出的信息,请参见以下各节。

皮林特 (Pylint)

Pylint is one of the oldest linters (circa 2006) and is still well-maintained. Some might call this software battle-hardened. It’s been around long enough that contributors have fixed most major bugs and the core features are well-developed.

皮林特(Pylint)是最古老的短绒棉之一(大约于2006年),至今仍得到很好的维护。 某些人可能称此软件为坚固的。 到现在为止,贡献者已经修复了大多数主要的错误,并且核心功能已经完善。

The common complaints against Pylint are that it is slow, too verbose by default, and takes a lot of configuration to get it working the way you want. Slowness aside, the other complaints are somewhat of a double-edged sword. Verbosity can be because of thoroughness. Lots of configuration can mean lots of adaptability to your preferences.

对Pylint的普遍抱怨是它运行缓慢,默认情况下太冗长,并且需要大量配置才能使其按您想要的方式工作。 除了缓慢,其他抱怨有点像一把双刃剑。 言过其实可能是因为彻底。 大量的配置可能意味着对您的首选项的适应性强。

Without further ado, the output after running Pylint against the lint-filled code from above:

事不宜迟,从上面对填充棉绒的代码运行Pylint之后的输出:

Note that I’ve condensed this with ellipses for similar lines. It’s quite a bit to take in, but there is a lot of lint in this code.

请注意,对于类似的线条,我已经用省略号将其压缩。 需要花很多时间,但是此代码中有很多皮棉。

Note that Pylint prefixes each of the problem areas with a R, C, W, E, or F, meaning:

请注意,Pylint用RCWEF为每个问题区域添加前缀,这意味着:

  • [R]efactor for a “good practice” metric violation
  • [C]onvention for coding standard violation
  • [W]arning for stylistic problems, or minor programming issues
  • [E]rror for important programming issues (i.e. most probably bug)
  • [F]atal for errors which prevented further processing
  • [R]违反“良好做法”指标的因素
  • [C]违反编码标准的发明
  • [W]警告样式问题或次要编程问题
  • [E]对于重要的编程问题(即很可能是错误)的错误
  • [F]致命错误,导致无法进一步处理

The above list is directly from Pylint’s user guide.

上面的列表直接来自Pylint的用户指南

PyFlakes (PyFlakes)

Pyflakes “makes a simple promise: it will never complain about style, and it will try very, very hard to never emit false positives”. This means that Pyflakes won’t tell you about missing docstrings or argument names not conforming to a naming style. It focuses on logical code issues and potential errors.

Pyflakes“做出了一个简单的承诺:它永远不会抱怨风格,并且会非常非常努力地避免产生误报”。 这意味着Pyflakes不会告诉您缺少不符合命名样式的文档字符串或参数名称。 它着重于逻辑代码问题和潜在错误。

The benefit here is speed. PyFlakes runs in a fraction of the time Pylint takes.

这样做的好处是速度。 PyFlakes的运行时间仅为Pylint花费的时间的一小部分。

Output after running against lint-filled code from above:

从上面运行填充了lint的代码后的输出:

code_with_lint.py:5: 'io' imported but unused
code_with_lint.py:6: 'from math import *' used; unable to detect undefined names
code_with_lint.py:14: local variable 'some_global_var' is assigned to but never used
code_with_lint.py:36: 'pi' may be undefined, or defined from star imports: math
code_with_lint.py:36: local variable 'list_comprehension' is assigned to but never used
code_with_lint.py:37: local variable 'time' (defined in enclosing scope on line 9) referenced before assignment
code_with_lint.py:37: local variable 'time' is assigned to but never used
code_with_lint.py:39: local variable 'date_and_time' is assigned to but never used
code_with_lint.py:5: 'io' imported but unused
code_with_lint.py:6: 'from math import *' used; unable to detect undefined names
code_with_lint.py:14: local variable 'some_global_var' is assigned to but never used
code_with_lint.py:36: 'pi' may be undefined, or defined from star imports: math
code_with_lint.py:36: local variable 'list_comprehension' is assigned to but never used
code_with_lint.py:37: local variable 'time' (defined in enclosing scope on line 9) referenced before assignment
code_with_lint.py:37: local variable 'time' is assigned to but never used
code_with_lint.py:39: local variable 'date_and_time' is assigned to but never used

The downside here is that parsing this output may be a bit more difficult. The various issues and errors are not labeled or organized by type. Depending on how you use this, that may not be a problem at all.

不利的一面是,解析此输出可能会更加困难。 各种问题和错误未按类型标记或组织。 根据您的使用方式,这可能根本不是问题。

pycodestyle(以前为pep8) (pycodestyle (formerly pep8))

Used to check some style conventions from PEP8. Naming conventions are not checked and neither are docstrings. The errors and warnings it does catch are categorized in this table.

用于检查PEP8中的某些样式约定。 不会检查命名约定,也不会检查文档字符串。 它确实捕获的错误和警告在此表中分类。

Output after running against lint-filled code from above:

从上面运行填充了lint的代码后的输出:

The nice thing about this output is that the lint is labeled by category. You can choose to ignore certain errors if you don’t care to adhere to a specific convention as well.

关于此输出的好处是,棉绒按类别标记。 如果您也不想遵守特定的约定,则可以选择忽略某些错误。

pydocstyle(以前是pep257) (pydocstyle (formerly pep257))

Very similar to pycodestyle, except instead of checking against PEP8 code style conventions, it checks docstrings against conventions from PEP257.

非常相似,pycodestyle,除了没有对PEP8代码样式约定检查,将检查与来自约定文档字符串PEP257

Output after running against lint-filled code from above:

从上面运行填充了lint的代码后的输出:

code_with_lint.py:1 at module level:
        D200: One-line docstring should fit on one line with quotes (found 3)
code_with_lint.py:1 at module level:
        D400: First line should end with a period (not '!')
code_with_lint.py:13 in public function `multiply`:
        D103: Missing docstring in public function
code_with_lint.py:20 in public function `is_sum_lucky`:
        D103: Missing docstring in public function
code_with_lint.py:31 in public class `SomeClass`:
        D101: Missing docstring in public class
code_with_lint.py:33 in public method `__init__`:
        D107: Missing docstring in __init__
code_with_lint.py:1 at module level:
        D200: One-line docstring should fit on one line with quotes (found 3)
code_with_lint.py:1 at module level:
        D400: First line should end with a period (not '!')
code_with_lint.py:13 in public function `multiply`:
        D103: Missing docstring in public function
code_with_lint.py:20 in public function `is_sum_lucky`:
        D103: Missing docstring in public function
code_with_lint.py:31 in public class `SomeClass`:
        D101: Missing docstring in public class
code_with_lint.py:33 in public method `__init__`:
        D107: Missing docstring in __init__

Again, like pycodestyle, pydocstyle labels and categorizes the various errors it finds. And the list doesn’t conflict with anything from pycodestyle since all the errors are prefixed with a D for docstring. A list of those errors can be found here.

再次,像pycodestyle一样,pydocstyle会对发现的各种错误进行标记和分类。 并且该列表与pycodestyle中的任何内容均不冲突,因为所有错误都以docstring前缀D 这些错误的列表可以在此处找到。

代码无毛 (Code Without Lint)

You can adjust the previously lint-filled code based on the linter’s output and you’ll end up with something like the following:

您可以根据linter的输出来调整先前填充了lint的代码,最终将得到以下内容:

That code is lint-free according to the linters above. While the logic itself is mostly nonsensical, you can see that at a minimum, consistency is enforced.

根据上面的lint,该代码是无绒的。 尽管逻辑本身大部分都是荒谬的,但您可以看到至少可以实现一致性。

In the above case, we ran linters after writing all the code. However, that’s not the only way to go about checking code quality.

在上述情况下,我们在编写所有代码后运行了linters。 但是,这不是检查代码质量的唯一方法。

什么时候可以检查代码质量? (When Can I Check My Code Quality?)

You can check your code’s quality:

您可以检查代码的质量:

  • As you write it
  • When it’s checked in
  • When you’re running your tests
  • 当你写的时候
  • 签入时
  • 运行测试时

It’s useful to have linters run against your code frequently. If automation and consistency aren’t there, it’s easy for a large team or project to lose sight of the goal and start creating lower quality code. It happens slowly, of course. Some poorly written logic or maybe some code with formatting that doesn’t match the neighboring code. Over time, all that lint piles up. Eventually, you can get stuck with something that’s buggy, hard to read, hard to fix, and a pain to maintain.

经常使linter与您的代码相对应很有用。 如果没有自动化和一致性,那么大型团队或项目很容易忽略目标并开始创建质量较低的代码。 当然,它发生得很慢。 一些写得不好的逻辑,或者某些格式与相邻代码不匹配的代码。 随着时间的流逝,所有的皮屑都会堆积起来。 最终,您可能会遇到一些错误,难以阅读,难以修复以及难以维护的问题。

To avoid that, check code quality often!

为避免这种情况,请经常检查代码质量!

当你写 (As You Write)

You can use linters as you write code, but configuring your environment to do so may take some extra work. It’s generally a matter of finding the plugin for your IDE or editor of choice. In fact, most IDEs will already have linters built in.

您可以在编写代码时使用linters,但是配置您的环境可能需要一些额外的工作。 通常,要找到适合您的IDE或所选编辑器的插件。 实际上,大多数IDE都已经内置了linter。

Here’s some general info on Python linting for various editors:

以下是针对各种编辑器的有关Python linting的一些常规信息:

签入代码之前 (Before You Check In Code)

If you’re using Git, Git hooks can be set up to run your linters before committing. Other version control systems have similar methods to run scripts before or after some action in the system. You can use these methods to block any new code that doesn’t meet quality standards.

如果您使用的是Git,则可以将Git钩子设置为在提交之前运行您的Linter。 其他版本控制系统具有类似的方法,可以在系统中的某些操作之前或之后运行脚本。 您可以使用这些方法来阻止任何不符合质量标准的新代码。

While this may seem drastic, forcing every bit of code through a screening for lint is an important step towards ensuring continued quality. Automating that screening at the front gate to your code may be the best way to avoid lint-filled code.

尽管这看起来很麻烦,但通过对棉绒进行筛选来强制每一位代码是确保持续质量的重要一步。 在您的代码的前门进行自动化筛选可能是避免皮棉填充代码的最佳方法。

运行测试时 (When Running Tests)

You can also place linters directly into whatever system you may use for continuous integration. The linters can be set up to fail the build if the code doesn’t meet quality standards.

您还可以将短毛绒直接放入可以用于持续集成的任何系统中。 如果代码不符合质量标准,则可以设置短绒以使构建失败。

Again, this may seem like a drastic step, especially if there are already lots of linter errors in the existing code. To combat this, some continuous integration systems will allow you the option of only failing the build if the new code increases the number of linter errors that were already present. That way you can start improving quality without doing a whole rewrite of your existing code base.

同样,这似乎是一个艰巨的步骤,特别是如果现有代码中已经存在很多linter错误。 为了解决这个问题,某些持续集成系统将允许您选择仅在新代码增加了已经存在的林特错误的情况下使构建失败的选项。 这样,您就可以开始提高质量,而无需完全重写现有代码库。

结论 (Conclusion)

High-quality code does what it’s supposed to do without breaking. It is easy to read, maintain, and extend. It functions without problems or defects and is written so that it’s easy for the next person to work with.

高质量的代码可以正常工作。 它易于阅读,维护和扩展。 它的功能没有问题或缺陷,并且编写得很容易,便于下一个人与之合作。

Hopefully it goes without saying that you should strive to have such high-quality code. Luckily, there are methods and tools to help improve code quality.

希望不用说,您应该努力拥有如此高质量的代码。 幸运的是,有一些方法和工具可以帮助提高代码质量。

Style guides will bring consistency to your code. PEP8 is a great starting point for Python. Linters will help you identify problem areas and inconsistencies. You can use linters throughout the development process, even automating them to flag lint-filled code before it gets too far.

样式指南将为您的代码带来一致性。 PEP8是Python的一个很好的起点。 Linters将帮助您确定问题区域和不一致之处。 您可以在整个开发过程中使用短绒,甚至可以在它们变得太远之前自动将短绒标记为填充短绒的代码。

Having linters complain about style also avoids the need for style discussions during code reviews. Some people may find it easier to receive candid feedback from these tools instead of a team member. Additionally, some team members may not want to “nitpick” style during code reviews. Linters avoid the politics, save time, and complain about any inconsistency.

让小子们抱怨样式也可以避免在代码审查期间进行样式讨论。 某些人可能会发现,从这些工具而不是团队成员那里收到坦率的反馈会更容易。 此外,某些团队成员可能不想在代码审查期间“挑剔”风格。 短毛回避政治,节省时间,并抱怨任何不一致之处。

In addition, all the linters mentioned in this article have various command line options and configurations that let you tailor the tool to your liking. You can be as strict or as loose as you want, which is an important thing to realize.

此外,本文提到的所有短毛猫都有各种命令行选项和配置,可让您根据自己的喜好定制该工具。 您可以根据需要严格或松散,这是很重要的一点。

Improving code quality is a process. You can take steps towards improving it without completely disallowing all nonconformant code. Awareness is a great first step. It just takes a person, like you, to first realize how important high-quality code is.

提高代码质量是一个过程。 您可以采取措施改进它,而不必完全禁止所有不合格的代码。 意识是伟大的第一步。 和您一样,只需要一个人就可以首先意识到高质量代码的重要性。

翻译自: https://www.pybloggers.com/2018/07/python-code-quality-tools-best-practices/

  • 0
    点赞
  • 0
    评论
  • 2
    收藏
  • 扫一扫,分享海报

参与评论 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值