python pep 8_如何使用PEP 8编写漂亮的Python代码

python pep 8

PEP 8, sometimes spelled PEP8 or PEP-8, is a document that provides guidelines and best practices on how to write Python code. It was written in 2001 by Guido van Rossom, Barry Warsaw, and Nick Coghlan. The primary focus of PEP 8 is to improve the readability and consistency of Python code.

PEP 8(有时拼写为PEP8或PEP-8)是一份文档,提供了有关如何编写Python代码的指南和最佳实践。 它由Guido van Rossom,Barry Warsaw和Nick Coghlan于2001年编写。 PEP 8的主要重点是提高Python代码的可读性和一致性。

PEP stands for Python Enhancement Proposal, and there are several of them. A PEP is a document that describes new features proposed for Python and documents aspects of Python, like design and style, for the community.

PEP代表Python增强提案,其中有几个。 PEP是一份文档,描述了为Python提议的新功能,并为社区记录了Python的各个方面,例如设计和风格。

This tutorial outlines the key guidelines laid out in PEP 8. It’s aimed at beginner to intermediate programmers, and as such I have not covered some of the most advanced topics. You can learn about these by reading the full PEP 8 documentation.

本教程概述了PEP 8中列出的关键准则。该指南针对初学者到中级程序员,因此,我没有涵盖某些最高级的主题。 您可以通过阅读完整的PEP 8文档来了解这些内容。

By the end of this tutorial, you’ll be able to:

在本教程结束时,您将能够

  • Write Python code that conforms to PEP 8
  • Understand the reasoning behind the guidelines laid out in PEP 8
  • Set up your development environment so that you can start writing PEP 8 compliant Python code
  • 编写符合PEP 8的Python代码
  • 了解PEP 8中列出的准则背后的原因
  • 设置您的开发环境,以便您可以开始编写符合PEP 8的Python代码

Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.

免费奖金: 关于Python精通的5个想法 ,这是针对Python开发人员的免费课程,向您展示了将Python技能提升到新水平所需的路线图和心态。

为什么我们需要PEP 8 (Why We Need PEP 8)

“Readability counts.”

“可读性很重要。”

— The Zen of Python

— Python的禅宗

PEP 8 exists to improve the readability of Python code. But why is readability so important? Why is writing readable code one of the guiding principles of the Python language?

存在PEP 8以提高Python代码的可读性。 但是为什么可读性如此重要? 为什么编写可读代码是Python语言的指导原则之一?

As Guido van Rossom said, “Code is read much more often than it is written.” You may spend a few minutes, or a whole day, writing a piece of code to process user authentication. Once you’ve written it, you’re never going to write it again. But you’ll definitely have to read it again. That piece of code might remain part of a project you’re working on. Every time you go back to that file, you’ll have to remember what that code does and why you wrote it, so readability matters.

正如Guido van Rossom所说,“代码的读取次数比其编写的次数更多。” 您可能需要花费几分钟或一整天的时间来编写一段代码来处理用户身份验证。 编写之后,就再也不会写了。 但是,您肯定必须再次阅读。 这段代码可能仍是您正在处理的项目的一部分。 每次回到该文件时,您都必须记住该代码的功能以及编写代码的原因,因此可读性很重要。

If you’re new to Python, it can be difficult to remember what a piece of code does a few days, or weeks, after you wrote it. If you follow PEP 8, you can be sure that you’ve named your variables well. You’ll know that you’ve added enough whitespace so it’s easier to follow logical steps in your code. You’ll also have commented your code well. All this will mean your code is more readable and easier to come back to. As a beginner, following the rules of PEP 8 can make learning Python a much more pleasant task.

如果您是Python的新手,那么可能很难记住在编写几天或几周后一段代码的功能。 如果遵循PEP 8,则可以确保已正确命名变量。 您会知道已经添加了足够的空格,因此可以更轻松地遵循代码中的逻辑步骤。 您还将很好地注释了您的代码。 所有这些都意味着您的代码更具可读性,并且更易于返回。 作为初学者,遵循PEP 8的规则可以使学习Python变得更加轻松。

Following PEP 8 is particularly important if you’re looking for a development job. Writing clear, readable code shows professionalism. It’ll tell an employer that you understand how to structure your code well.

如果您正在寻找开发工作,那么遵循PEP 8尤其重要。 编写清晰易读的代码表明专业。 它将告诉雇主您了解如何很好地构造代码。

If you have more experience writing Python code, then you may need to collaborate with others. Writing readable code here is crucial. Other people, who may have never met you or seen your coding style before, will have to read and understand your code. Having guidelines that you follow and recognize will make it easier for others to read your code.

如果您有更多编写Python代码的经验,那么您可能需要与他人合作。 在此处编写可读代码至关重要。 其他人,可能从未见过您或从未见过您的编码风格,将不得不阅读并理解您的代码。 遵循并认识到准则将使其他人更容易阅读您的代码。

命名约定 (Naming Conventions)

“Explicit is better than implicit.”

“显式胜于隐式。”

— The Zen of Python

— Python的禅宗

When you write Python code, you have to name a lot of things: variables, functions, classes, packages, and so on. Choosing sensible names will save you time and energy later. You’ll be able to figure out, from the name, what a certain variable, function, or class represents. You’ll also avoid using inappropriate names that might result in errors that are difficult to debug.

在编写Python代码时,您必须命名很多东西:变量,函数,类,包等等。 选择明智的名称将在以后节省您的时间和精力。 您可以从名称中找出某个变量,函数或类的含义。 您还将避免使用不合适的名称,这可能会导致难以调试的错误。

Note: Never use l, O, or I single letter names as these can be mistaken for 1 and 0, depending on typeface:

注意 :切勿使用lOI单字母名称,因为根据字体的不同,这些名称可能会误认为10

 O O = = 2  2  # This may look like you're trying to reassign 2 to zero
# This may look like you're trying to reassign 2 to zero

命名样式 (Naming Styles)

The table below outlines some of the common naming styles in Python code and when you should use them:

下表概述了Python代码中的一些常见命名样式以及何时使用它们:

Type 类型 Naming Convention 命名约定 Examples 例子
Function 功能 Use a lowercase word or words. Separate words by underscores to improve readability. 使用一个或多个小写单词。 用下划线将单词分开,以提高可读性。 function, functionmy_functionmy_function
Variable 变量 Use a lowercase single letter, word, or words. Separate words with underscores to improve readability. 使用小写字母,单词或单词。 用下划线分隔单词以提高可读性。 x, xvar, varmy_variablemy_variable
ClassStart each word with a capital letter. Do not separate words with underscores. This style is called camel case. 每个单词以大写字母开头。 不要用下划线分隔单词。 这种样式称为骆驼皮套。 Model, ModelMyClassMyClass
Method 方法 Use a lowercase word or words. Separate words with underscores to improve readability. 使用一个或多个小写单词。 用下划线分隔单词以提高可读性。 class_method, class_methodmethodmethod
Constant 不变 Use an uppercase single letter, word, or words. Separate words with underscores to improve readability. 使用大写单个字母,单词或单词。 用下划线分隔单词以提高可读性。 CONSTANT, CONSTANTMY_CONSTANT, MY_CONSTANTMY_LONG_CONSTANTMY_LONG_CONSTANT
Module 模组 Use a short, lowercase word or words. Separate words with underscores to improve readability. 使用简短的小写单词或多个单词。 用下划线分隔单词以提高可读性。 module.py, module.pymy_module.pymy_module.py
PackageUse a short, lowercase word or words. Do not separate words with underscores. 使用简短的小写单词或多个单词。 不要用下划线分隔单词。 package, packagemypackagemypackage

These are some of the common naming conventions and examples of how to use them. But in order to write readable code, you still have to be careful with your choice of letters and words. In addition to choosing the correct naming styles in your code, you also have to choose the names carefully. Below are a few pointers on how to do this as effectively as possible.

这些是一些常见的命名约定以及如何使用它们的示例。 但是,为了编写可读的代码,您仍然必须谨慎选择字母和单词。 除了在代码中选择正确的命名样式外,还必须仔细选择名称。 以下是有关如何尽可能有效地执行此操作的一些指导。

如何选择名字 (How to Choose Names)

Choosing names for your variables, functions, classes, and so forth can be challenging. You should put a fair amount of thought into your naming choices when writing code as it will make your code more readable. The best way to name your objects in Python is to use descriptive names to make it clear what the object represents.

为变量,函数,类等选择名称可能具有挑战性。 在编写代码时,您应该在命名选择上多加考虑,因为这会使您的代码更具可读性。 用Python命名对象的最好方法是使用描述性名称,以明确对象的含义。

When naming variables, you may be tempted to choose simple, single-letter lowercase names, like x. But, unless you’re using x as the argument of a mathematical function, it’s not clear what x represents. Imagine you are storing a person’s name as a string, and you want to use string slicing to format their name differently. You could end up with something like this:

在命名变量时,您可能会倾向于选择简单的单字母小写名称,例如x 。 但是,除非您将x用作数学函数的参数,否则不清楚x代表什么。 假设您将一个人的姓名存储为字符串,并且想要使用字符串切片将其姓名格式不同。 您可能最终会得到这样的结果:

This will work, but you’ll have to keep track of what x, y, and z represent. It may also be confusing for collaborators. A much clearer choice of names would be something like this:

这将起作用,但是您必须跟踪xyz代表什么。 这也可能使合作者感到困惑。 更清晰的名称选择如下所示:

 >>> >>>  # Recommended
# Recommended
>>> >>>  name name = = 'John Smith'
'John Smith'
>>> >>>  first_namefirst_name , , last_name last_name = = namename .. splitsplit ()
()
>>> >>>  printprint (( last_namelast_name , , first_namefirst_name , , sepsep == ', '', ' )
)
'Smith, John'
'Smith, John'

Similarly, to reduce the amount of typing you do, it can be tempting to use abbreviations when choosing names. In the example below, I have defined a function db() that takes a single argument x and doubles it:

同样,为了减少键入的次数,选择名称时可能会使用缩写。 在下面的示例中,我定义了一个函数db() ,该函数接受单个参数x并将其加倍:

At first glance, this could seem like a sensible choice. db() could easily be an abbreviation for double. But imagine coming back to this code in a few days. You may have forgotten what you were trying to achieve with this function, and that would make guessing how you abbreviated it difficult.

乍一看,这似乎是一个明智的选择。 db()可以很容易地是double的缩写。 但是,想象几天后回到此代码。 您可能已经忘记了使用此功能要实现的目标,而这将使您很难猜测其缩写。

The following example is much clearer. If you come back to this code a couple of days after writing it, you’ll still be able to read and understand the purpose of this function:

以下示例更加清晰。 如果您在编写此代码后几天回到此代码,则仍可以阅读并理解此函数的用途:

 # Recommended
# Recommended
def def multiply_by_twomultiply_by_two (( xx ):
    ):
    return return x x * * 2
2

The same philosophy applies to all other data types and objects in Python. Always try to use the most concise but descriptive names possible.

相同的原理适用于Python中的所有其他数据类型和对象。 始终尝试使用最简洁但描述性强的名称。

代码布局 (Code Layout)

“Beautiful is better than ugly.”

“美丽胜于丑陋。”

— The Zen of Python

— Python的禅宗

How you lay out your code has a huge role in how readable it is. In this section, you’ll learn how to add vertical whitespace to improve the readability of your code. You’ll also learn how to handle the 79 character line limit recommended in PEP 8.

代码的布局方式在可读性方面起着巨大的作用。 在本节中,您将学习如何添加垂直空格以提高代码的可读性。 您还将学习如何处理PEP 8中建议的79个字符的行限制。

空行 (Blank Lines)

Vertical whitespace, or blank lines, can greatly improve the readability of your code. Code that’s bunched up together can be overwhelming and hard to read. Similarly, too many blank lines in your code makes it look very sparse, and the reader might need to scroll more than necessary. Below are three key guidelines on how to use vertical whitespace.

垂直空格或空白行可以大大提高代码的可读性。 聚集在一起的代码可能会让人难以理解并且难以理解。 同样,代码中的空白行过多会使它看起来很稀疏,并且读者可能需要滚动更多不必要的内容。 以下是有关如何使用垂直空白的三个关键准则。

Surround top-level functions and classes with two blank lines. Top-level functions and classes should be fairly self-contained and handle separate functionality. It makes sense to put extra vertical space around them, so that it’s clear they are separate:

用两个空行包围顶级函数和类。 顶级函数和类应完全独立并且可以处理单独的功能。 在它们周围放置额外的垂直空间是很有意义的,这样很显然它们是分开的:

Surround method definitions inside classes with a single blank line. Inside a class, functions are all related to one another. It’s good practice to leave only a single line between them:

将类内的方法定义用单个空行括起来。 在一个类中,函数都是相互关联的。 最好在两者之间只留一行:

 class class MyClassMyClass :
    :
    def def first_methodfirst_method (( selfself ):
        ):
        return return None

    None

    def def second_methodsecond_method (( selfself ):
        ):
        return return None
None

Use blank lines sparingly inside functions to show clear steps. Sometimes, a complicated function has to complete several steps before the return statement. To help the reader understand the logic inside the function, it can be helpful to leave a blank line between each step.

在函数内部保留空白行,以显示清晰的步骤。 有时,复杂的函数必须在return语句之前完成几个步骤。 为了帮助读者理解函数内部的逻辑,在每个步骤之间留一个空白行会很有帮助。

In the example below, there is a function to calculate the variance of a list. This is two-step problem, so I have indicated each step by leaving a blank line between them. There is also a blank line before the return statement. This helps the reader clearly see what’s returned:

在下面的示例中,有一个函数可以计算列表的方差。 这是两个步骤的问题,因此,我在每个步骤之间都留了一条空白行,以指示每个步骤。 return语句之前还有一个空行。 这有助于读者清楚地看到返回的内容:

If you use vertical whitespace carefully, it can greatly improved the readability of your code. It helps the reader visually understand how your code splits up into sections, and how those sections relate to one another.

如果仔细使用垂直空格,则可以大大提高代码的可读性。 它可以帮助读者直观地了解您的代码如何拆分为多个部分,以及这些部分如何相互关联。

最大行长和断行 (Maximum Line Length and Line Breaking)

PEP 8 suggests lines should be limited to 79 characters. This is because it allows you to have multiple files open next to one another, while also avoiding line wrapping.

PEP 8建议将行数限制为79个字符。 这是因为它允许您将多个文件彼此相邻打开,同时还避免了换行。

Of course, keeping statements to 79 characters or less is not always possible. PEP 8 outlines ways to allow statements to run over several lines.

当然,保持语句不超过79个字符并非总是可能的。 PEP 8概述了允许语句跨几行运行的方法。

Python will assume line continuation if code is contained within parentheses, brackets, or braces:

如果代码包含在括号,方括号或花括号中,则Python将假定行继续:

 def def functionfunction (( arg_onearg_one , , arg_twoarg_two ,
             ,
             arg_threearg_three , , arg_fourarg_four ):
    ):
    return return arg_one
arg_one

If it is impossible to use implied continuation, then you can use backslashes to break lines instead:

如果不可能使用隐式连续,则可以使用反斜杠来换行:

However, if you can use implied continuation, then you should do so.

但是,如果可以使用隐式延续,则应该这样做。

If line breaking needs to occur around binary operators, like + and *, it should occur before the operator. This rule stems from mathematics. Mathematicians agree that breaking before binary operators improves readability. Compare the following two examples.

如果换行需要在+*类的二进制运算符周围发生,则应在运算符之前发生。 这个规则源于数学。 数学家一致认为,在二元运算符之前执行中断可提高可读性。 比较以下两个示例。

Below is an example of breaking before a binary operator:

下面是在二进制运算符之前中断的示例:

 # Recommended
# Recommended
total total = = (( first_variable
         first_variable
         + + second_variable
         second_variable
         - - third_variablethird_variable )
)

You can immediately see which variable is being added or subtracted, as the operator is right next to the variable being operated on.

您可以立即看到要添加或减去的变量,因为运算符就在要操作的变量旁边。

Now, let’s see an example of breaking after a binary operator:

现在,让我们来看一个破坏二进制运算符的示例:

Here, it’s harder to see which variable is being added and which is subtracted.

在这里,很难看到要添加哪个变量和减去哪个变量。

Breaking before binary operators produces more readable code, so PEP 8 encourages it. Code that consistently breaks after a binary operator is still PEP 8 compliant. However, you’re encouraged to break before a binary operator.

在二进制运算符产生更易读的代码之前先行破解,因此PEP 8鼓励这样做。 在二进制运算符仍然符合PEP 8之后,始终中断的代码。 但是,建议您在二进制运算符之前使用。

缩进 (Indentation)

“There should be one—and preferably only one—obvious way to do it.”

“应该有一种明显的方法,最好只有一种。”

— The Zen of Python

— Python的禅宗

Indentation, or leading whitespace, is extremely important in Python. The indentation level of lines of code in Python determines how statements are grouped together.

缩进或前导空格在Python中极为重要。 Python中代码行的缩进级别决定了如何将语句组合在一起。

Consider the following example:

考虑以下示例:

 x x = = 3
3
if if x x > > 55 :
    :
    printprint (( 'x is larger than 5''x is larger than 5' )
)

The indented print statement lets Python know that it should only be executed if the if statement returns True. The same indentation applies to tell Python what code to execute when a function is called or what code belongs to a given class.

缩进的print语句让Python知道仅当if语句返回True时才应执行该语句。 相同的缩进适用于告诉Python调用函数时要执行什么代码,或者属于给定类的代码。

The key indentation rules laid out by PEP 8 are the following:

PEP 8制定的关键缩进规则如下:

  • Use 4 consecutive spaces to indicate indentation.
  • Prefer spaces over tabs.
  • 使用4个连续的空格表示缩进。
  • 在标签上优先使用空格。

制表符与空格 (Tabs vs. Spaces)

As mentioned above, you should use spaces instead of tabs when indenting code. You can adjust the settings in your text editor to output 4 spaces instead of a tab character, when you press the Tab key.

如上所述,缩进代码时应使用空格而不是制表符。 当您按Tab键时,可以在文本编辑器中调整设置以输出4个空格而不是制表符。

If you’re using Python 2 and have used a mixture of tabs and spaces to indent your code, you won’t see errors when trying to run it. To help you to check consistency, you can add a -t flag when running Python 2 code from the command line. The interpreter will issue warnings when you are inconsistent with your use of tabs and spaces:

如果您使用的是Python 2,并且使用了制表符和空格的组合来缩进代码,则在尝试运行它时不会看到错误。 为了帮助您检查一致性,可以在从命令行运行Python 2代码时添加-t标志。 当您与制表符和空格的使用不一致时,解释器将发出警告:

If, instead, you use the -tt flag, the interpreter will issue errors instead of warnings, and your code will not run. The benefit of using this method is that the interpreter tells you where the inconsistencies are:

相反,如果使用-tt标志,则解释器将发出错误而不是警告,并且代码将无法运行。 使用此方法的好处是解释器会告诉您不一致之处在哪里:

 $ python2 -tt code.py
$ python2 -tt code.py
  File "code.py", line 3
  File "code.py", line 3
    print(i, j)
    print(i, j)
             ^
             ^
TabError: inconsistent use of tabs and spaces in indentation
TabError: inconsistent use of tabs and spaces in indentation

Python 3 does not allow mixing of tabs and spaces. Therefore, if you are using Python 3, then these errors are issued automatically:

Python 3不允许混合使用制表符和空格。 因此,如果您使用的是Python 3,则会自动发出以下错误:

You can write Python code with either tabs or spaces indicating indentation. But, if you’re using Python 3, you must be consistent with your choice. Otherwise, your code will not run. PEP 8 recommends that you always use 4 consecutive spaces to indicate indentation.

您可以使用制表符或空格表示缩进来编写Python代码。 但是,如果您使用的是Python 3,则必须与您的选择保持一致。 否则,您的代码将无法运行。 PEP 8建议您始终使用4个连续的空格来表示缩进。

换行后的缩进 (Indentation Following Line Breaks)

When you’re using line continuations to keep lines to under 79 characters, it is useful to use indentation to improve readability. It allows the reader to distinguish between two lines of code and a single line of code that spans two lines. There are two styles of indentation you can use.

当您使用连续行将行数保持在79个字符以下时,使用缩进可提高可读性很有用。 它使读者可以区分两行代码和跨两行的一行代码。 您可以使用两种缩进样式。

The first of these is to align the indented block with the opening delimiter:

首先是将缩进的块与开口定界符对齐:

 def def functionfunction (( arg_onearg_one , , arg_twoarg_two ,
             ,
             arg_threearg_three , , arg_fourarg_four ):
    ):
    return return arg_one
arg_one

Sometimes you can find that only 4 spaces are needed to align with the opening delimiter. This will often occur in if statements that span multiple lines as the if, space, and opening bracket make up 4 characters. In this case, it can be difficult to determine where the nested code block inside the if statement begins:

有时您会发现仅需要4个空格即可与分隔符对齐。 这种情况通常会发生在if语句跨越多行的if ,因为if ,空格和左括号组成4个字符。 在这种情况下,可能很难确定if语句中嵌套代码块的开始位置:

In this case, PEP 8 provides two alternatives to help improve readability:

在这种情况下,PEP 8提供了两种选择来帮助提高可读性:

  • Add a comment after the final condition. Due to syntax highlighting in most editors, this will separate the conditions from the nested code:

    x = 5
    if (x > 3 and
        x < 10):
        # Both conditions satisfied
        print(x)
    
    
  • Add extra indentation on the line continuation:

  • 在最终条件之后添加评论。 由于大多数编辑器中都突出显示了语法,因此这会将条件与嵌套代码分开:

     x = 5
    if ( x > 3 and
        x < 10 ):
        # Both conditions satisfied
        print ( x )
    
  • 在行继续处添加额外的缩进:

An alternative style of indentation following a line break is a hanging indent. This is a typographical term meaning that every line but the first in a paragraph or statement is indented. You can use a hanging indent to visually represent a continuation of a line of code. Here’s an example:

换行后的另一种缩进方式悬挂式缩进 。 这是印刷术语,表示除段落或语句中的第一行外的所有行都缩进。 您可以使用悬挂缩进来直观地表示一行代码的延续。 这是一个例子:

 var var = = functionfunction (
    (
    arg_onearg_one , , arg_twoarg_two ,
    ,
    arg_threearg_three , , arg_fourarg_four )
)

Note: When you’re using a hanging indent, there must not be any arguments on the first line. The following example is not PEP 8 compliant:

注意 :使用悬挂式缩进时,第一行上不得有任何参数。 以下示例不符合PEP 8:

When using a hanging indent, add extra indentation to distinguish the continued line from code contained inside the function. The following example is difficult to read because the code inside the function is at the same indentation level as the continued lines:

使用悬挂缩进时,请添加额外的缩进以将续行与函数中包含的代码区分开。 下面的示例很难阅读,因为函数内部的代码与续行的缩进级别相同:

 # Not Recommended
# Not Recommended
def def functionfunction (
    (
    arg_onearg_one , , arg_twoarg_two ,
    ,
    arg_threearg_three , , arg_fourarg_four ):
    ):
    return return arg_one
arg_one

Instead, it’s better to use a double indent on the line continuation. This helps you to distinguish between function arguments and the function body, improving readability:

相反,最好在行继续处使用双缩进。 这可以帮助您区分函数参数和函数主体,从而提高可读性:

When you write PEP 8 compliant code, the 79 character line limit forces you to add line breaks in your code. To improve readability, you should indent a continued line to show that it is a continued line. There are two ways of doing this. The first is to align the indented block with the opening delimiter. The second is to use a hanging indent. You are free to chose which method of indentation you use following a line break.

在编写符合PEP 8的代码时,79个字符的行限制会强制您在代码中添加换行符。 为了提高可读性,您应该缩进连续行以表明它是连续行。 有两种方法可以做到这一点。 首先是将缩进的块与开口定界符对齐。 第二种是使用悬挂缩进。 您可以自由选择在换行后使用哪种缩进方法。

在哪里放置结束括号 (Where to Put the Closing Brace)

Line continuations allow you to break lines inside parentheses, brackets, or braces. It’s easy to forget about the closing brace, but it’s important to put it somewhere sensible. Otherwise, it can confuse the reader. PEP 8 provides two options for the position of the closing brace in implied line continuations:

行的延续使您可以在括号,方括号或大括号内使行折断。 很容易忘记括号,但是将其放在明智的位置很重要。 否则,可能会使读者感到困惑。 PEP 8为隐式连续行中的闭合撑杆提供了两种选择:

  • Line up the closing brace with the first non-whitespace character of the previous line:

    list_of_numbers = [
        1, 2, 3,
        4, 5, 6,
        7, 8, 9
        ]
    
    
  • Line up the closing brace with the first character of the line that starts the construct:

  • 将右括号与上一行的第一个非空白字符对齐:

     list_of_numbers = [
        1 , 2 , 3 ,
        4 , 5 , 6 ,
        7 , 8 , 9
        ]
    
  • 将右括号与开始构造的行的第一个字符对齐:

You are free to chose which option you use. But, as always, consistency is key, so try to stick to one of the above methods.

您可以自由选择使用哪个选项。 但是,与以往一样,一致性是关键,因此请尝试使用上述方法之一。

注释 (Comments)

“If the implementation is hard to explain, it’s a bad idea.”

“如果实施难以解释,那是个坏主意。”

— The Zen of Python

— Python的禅宗

You should use comments to document code as it’s written. It is important to document your code so that you, and any collaborators, can understand it. When you or someone else reads a comment, they should be able to easily understand the code the comment applies to and how it fits in with the rest of your code.

您应该使用注释来记录编写的代码。 记录您的代码很重要,这样您和任何协作者都可以理解它。 当您或其他人阅读注释时,他们应该能够容易地理解注释所适用的代码以及它与其余代码的适应性。

Here are some key points to remember when adding comments to your code:

在代码中添加注释时,请记住以下几点:

  • Limit the line length of comments and docstrings to 72 characters.
  • Use complete sentences, starting with a capital letter.
  • Make sure to update comments if you change your code.
  • 将注释和文档字符串的行长度限制为72个字符。
  • 使用完整的句子,从大写字母开始。
  • 如果更改代码,请确保更新注释。

阻止评论 (Block Comments)

Use block comments to document a small section of code. They are useful when you have to write several lines of code to perform a single action, such as importing data from a file or updating a database entry. They are important as they help others understand the purpose and functionality of a given code block.

使用块注释来记录一小段代码。 当您必须编写多行代码来执行单个操作(例如从文件导入数据或更新数据库条目)时,它们很有用。 它们很重要,因为它们可以帮助其他人理解给定代码块的目的和功能。

PEP 8 provides the following rules for writing block comments:

PEP 8为编写块注释提供了以下规则:

  • Indent block comments to the same level as the code they describe.
  • Start each line with a # followed by a single space.
  • Separate paragraphs by a line containing a single #.
  • 将块注释缩进到与其描述的代码相同的级别。
  • 每行以#开头,后跟一个空格。
  • 用包含单个#的行将段落分开。

Here is a block comment explaining the function of a for loop. Note that the sentence wraps to a new line to preserve the 79 character line limit:

这是一个块注释, for解释for循环的功能。 请注意,该句子将换行以保留79个字符的行限制:

 for for i i in in rangerange (( 00 , , 1010 ):
    ):
    # Loop over i ten times and print out the value of i, followed by a
    # Loop over i ten times and print out the value of i, followed by a
    # new line character
    # new line character
    printprint (( ii , , '' nn '' )
)

Sometimes, if the code is very technical, then it is necessary to use more than one paragraph in a block comment:

有时,如果代码非常技术性,则有必要在块注释中使用多个段落:

If you’re ever in doubt as to what comment type is suitable, then block comments are often the way to go. Use them as much as possible throughout your code, but make sure to update them if you make changes to your code!

如果您不确定哪种注释类型合适,那么通常可以使用阻止注释。 在整个代码中尽可能使用它们,但是如果对代码进行了更改,请确保对其进行更新!

内联评论 (Inline Comments)

Inline comments explain a single statement in a piece of code. They are useful to remind you, or explain to others, why a certain line of code is necessary. Here’s what PEP 8 has to say about them:

内联注释在一段代码中解释了一条语句。 它们对于提醒您或向其他人解释为什么需要一定的代码行很有用。 以下是PEP 8对他们的评价:

  • Use inline comments sparingly.
  • Write inline comments on the same line as the statement they refer to.
  • Separate inline comments by two or more spaces from the statement.
  • Start inline comments with a # and a single space, like block comments.
  • Don’t use them to explain the obvious.
  • 谨慎使用内联注释。
  • 在与其引用的语句相同的行上编写内联注释。
  • 将内联注释与语句分开两个或多个空格。
  • #和一个空格开头的内联注释,例如块注释。
  • 不要用它们来解释显而易见的东西。

Below is an example of an inline comment:

以下是嵌入式注释的示例:

 x x = = 5  5  # This is an inline comment
# This is an inline comment

Sometimes, inline comments can seem necessary, but you can use better naming conventions instead. Here’s an example:

有时,内联注释似乎很必要,但是您可以使用更好的命名约定。 这是一个例子:

Here, the inline comment does give extra information. However using x as a variable name for a person’s name is bad practice. There’s no need for the inline comment if you rename your variable:

在此,内联注释确实提供了更多信息。 但是,将x用作人名的变量名是不好的做法。 如果重命名变量,则不需要内联注释:

 student_name student_name = = 'John Smith'
'John Smith'

Finally, inline comments such as these are bad practice as they state the obvious and clutter code:

最后,诸如此类的内联注释是不好的做法,因为它们陈述了明显且混乱的代码:

Inline comments are more specific than block comments, and it’s easy to add them when they’re not necessary, which leads to clutter. You could get away with only using block comments so, unless you are sure you need an inline comment, your code is more likely to be PEP 8 compliant if you stick to block comments.

内联注释比块注释更具体,并且在不需要它们时很容易添加它们,这会导致混乱。 您可以只使用阻止注释,因此,除非您确定需要嵌入式注释,否则如果您坚持阻止注释,则您的代码更有可能符合PEP 8。

文档字符串 (Documentation Strings)

Documentation strings, or docstrings, are strings enclosed in double (""") or single (''') quotation marks that appear on the first line of any function, class, method, or module. You can use them to explain and document a specific block of code. There is an entire PEP, PEP 257, that covers docstrings, but you’ll get a summary in this section.

文档字符串或文档字符串是用双引号( """ )或单引号( ''' )引起的字符串,它们出现在任何函数,类,方法或模块的第一行。您可以使用它们来解释和记录文档一个特定的代码块,其中有一个完整的PEP, PEP 257 ,涵盖了文档字符串,但是您将在本节中获得一个摘要。

The most important rules applying to docstrings are the following:

适用于文档字符串的最重要规则如下:

  • Surround docstrings with three double quotes on either side, as in """This is a docstring""".

  • Write them for all public modules, functions, classes, and methods.

  • Put the """ that ends a multiline docstring on a line by itself:

    def quadratic(a, b, c, x):
        """Solve quadratic equation via the quadratic formula.
    
        A quadratic equation has the following form:
        ax**2 + bx + c = 0
    
        There always two solutions to a quadratic equation: x_1 & x_2.
        """
        x_1 = (- b+(b**2-4*a*c)**(1/2)) / (2*a)
        x_2 = (- b-(b**2-4*a*c)**(1/2)) / (2*a)
    
        return x_1, x_2
    
    
  • For one-line docstrings, keep the """ on the same line:

  • 用两边的双引号引起来的文档字符串括起来,如"""This is a docstring"""

  • 为所有公共模块,函数,类和方法编写它们。

  • 将多行文档字符串结尾的"""单独放在一行上:

     def quadratic ( a , b , c , x ):
        """Solve quadratic equation via the quadratic formula.
    
        A quadratic equation has the following form:
        ax**2 + bx + c = 0
    
        There always two solutions to a quadratic equation: x_1 & x_2.
        """
        x_1 = ( - b + ( b ** 2 - 4 * a * c ) ** ( 1 / 2 )) / ( 2 * a )
        x_2 = ( - b - ( b ** 2 - 4 * a * c ) ** ( 1 / 2 )) / ( 2 * a )
    
        return x_1 , x_2
    
  • 对于单行文档字符串,请将"""放在同一行:

For a more detailed article on documenting Python code, see Documenting Python Code: A Complete Guide by James Mertz.

有关记录Python代码的更详细的文章,请参阅James Mertz的“记录Python代码:完整指南”

表达式和语句中的空格 (Whitespace in Expressions and Statements)

“Sparse is better than dense.”

“稀疏胜于密集。”

— The Zen of Python

— Python的禅宗

Whitespace can be very helpful in expressions and statements when used properly. If there is not enough whitespace, then code can be difficult to read, as it’s all bunched together. If there’s too much whitespace, then it can be difficult to visually combine related terms in a statement.

如果正确使用空格,则在表达式和语句中非常有用。 如果没有足够的空格,那么代码可能很难阅读,因为它们都聚集在一起。 如果空格过多,则可能很难在语句中直观地组合相关术语。

二元运算符周围的空白 (Whitespace Around Binary Operators)

Surround the following binary operators with a single space on either side:

将以下二进制运算符两边用单个空格括起来:

  • Assignment operators (=, +=, -=, and so forth)

  • Comparisons (==, !=, >, <. >=, <=) and (is, is not, in, not in)

  • Booleans (and, not, or)

  • 赋值运算符( =+=-=等)

  • 比较( ==!=><>=<= )和( isis notininnot in

  • 布尔值( andnot or

Note: When = is used to assign a default value to a function argument, do not surround it with spaces.

注意 :当使用=将默认值分配给函数参数时,请不要用空格包围。

 # Recommended
# Recommended
def def functionfunction (( default_parameterdefault_parameter == 55 ):
    ):
    # ...


# ...


# Not recommended
# Not recommended
def def functionfunction (( default_parameter default_parameter = = 55 ):
    ):
    # ...
# ...

When there’s more than one operator in a statement, adding a single space before and after each operator can look confusing. Instead, it is better to only add whitespace around the operators with the lowest priority, especially when performing mathematical manipulation. Here are a couple examples:

如果一个语句中有多个运算符,则在每个运算符前后添加一个空格可能会造成混淆。 相反,最好仅在优先级最低的运算符周围添加空格,尤其是在执行数学运算时。 这是几个例子:

You can also apply this to if statements where there are multiple conditions:

您还可以将其应用于具有多个条件的if语句:

 # Not recommended
# Not recommended
if if x x > > 5 5 and and x x % % 2 2 == == 00 :
    :
    printprint (( 'x is larger than 5 and divisible by 2!''x is larger than 5 and divisible by 2!' )
)

In the above example, the and operator has lowest priority. It may therefore be clearer to express the if statement as below:

在上面的示例中, and运算符的优先级最低。 因此,将if语句表达如下可能更清楚:

You are free to choose which is clearer, with the caveat that you must use the same amount of whitespace either side of the operator.

您可以自由选择哪个更清晰,但需要注意的是,您必须在运算符的两边都使用相同数量的空格。

The following is not acceptable:

以下是不可接受的:

 # Definitely do not do this!
# Definitely do not do this!
if if x x >> 5 5 and and xx % % 22 == == 00 :
    :
    printprint (( 'x is larger than 5 and divisible by 2!''x is larger than 5 and divisible by 2!' )
)

In slices, colons act as a binary operators. Therefore, the rules outlined in the previous section apply, and there should be the same amount of whitespace either side. The following examples of list slices are valid:

在分片中,冒号充当二进制运算符。 因此,上一节中概述的规则适用,并且每侧都应有相同数量的空格。 以下列表切片示例有效:

In summary, you should surround most operators with whitespace. However, there are some caveats to this rule, such as in function arguments or when you’re combining multiple operators in one statement.

总而言之,您应该用空格将大多数运算符括起来。 但是,此规则有一些警告,例如在函数参数中或在一个语句中组合多个运算符时。

何时避免添加空格 (When to Avoid Adding Whitespace)

In some cases, adding whitespace can make code harder to read. Too much whitespace can make code overly sparse and difficult to follow. PEP 8 outlines very clear examples where whitespace is inappropriate.

在某些情况下,添加空格会使代码难以阅读。 过多的空格会使代码过于稀疏,难以遵循。 PEP 8概述了空格不适当的非常清晰的示例。

The most important place to avoid adding whitespace is at the end of a line. This is known as trailing whitespace. It is invisible and can produce errors that are difficult to trace.

避免添加空格的最重要的地方是在行的末尾。 这称为尾随空白 。 它是不可见的,并且可能产生难以跟踪的错误。

The following list outlines some cases where you should avoid adding whitespace:

以下列表概述了应避免添加空格的一些情况:

  • Immediately inside parentheses, brackets, or braces:

    # Recommended
    my_list = [1, 2, 3]
    
    # Not recommended
    my_list = [ 1, 2, 3, ]
    
    
  • Before a comma, semicolon, or colon:

  • Before the open parenthesis that starts the argument list of a function call:

    def double(x):
        return x * 2
    
    # Recommended
    double(3)
    
    # Not recommended
    double (3)
    
    
  • Before the open bracket that starts an index or slice:

  • Between a trailing comma and a closing parenthesis:

    # Recommended
    tuple = (1,)
    
    # Not recommended
    tuple = (1, )
    
    
  • To align assignment operators:

  • 紧靠在括号,方括号或大括号内:

     # Recommended
    my_list = [ 1 , 2 , 3 ]
    
    # Not recommended
    my_list = [ 1 , 2 , 3 , ]
    
  • 在逗号,分号或冒号之前:

  • 在开始括号的函数调用的参数列表之前:

     def double ( x ):
        return x * 2
    
    # Recommended
    double ( 3 )
    
    # Not recommended
    double ( 3 )
    
  • 在开始索引或切片的方括号之前:

  • 在逗号和右括号之间:

     # Recommended
    tuple = ( 1 ,)
    
    # Not recommended
    tuple = ( 1 , )
    
  • 对齐赋值运算符:

Make sure that there is no trailing whitespace anywhere in your code. There are other cases where PEP 8 discourages adding extra whitespace, such as immediately inside brackets, as well as before commas and colons. You should also never add extra whitespace in order to align operators.

确保代码中的任何地方都没有尾随空格。 在其他情况下,PEP 8不鼓励添加额外的空格,例如在括号内以及逗号和冒号之前。 您也不应添加额外的空格以对齐运算符。

编程建议 (Programming Recommendations)

“Simple is better than complex.”

“简单胜于复杂。”

— The Zen of Python

— Python的禅宗

You will often find that there are several ways to perform a similar action in Python (and any other programming language for that matter). In this section, you’ll see some of the suggestions PEP 8 provides to remove that ambiguity and preserve consistency.

您通常会发现有几种方法可以在Python(以及与此相关的任何其他编程语言)中执行类似的操作。 在本节中,您将看到PEP 8提供的一些建议,以消除这种歧义并保持一致性。

Don’t compare boolean values to True or False using the equivalence operator. You’ll often need to check if a boolean value is True or False. When doing so, it is intuitive to do this with a statement like the one below:

不要使用等效运算符将布尔值与TrueFalse进行比较。 您通常需要检查布尔值是True还是False。 这样做时,使用如下所示的语句很直观:

 # Not recommended
# Not recommended
my_bool my_bool = = 6 6 > > 5
5
if if my_bool my_bool == == TrueTrue :
    :
    return return '6 is bigger than 5'
'6 is bigger than 5'

The use of the equivalence operator, ==, is unnecessary here. bool can only take values True or False. It is enough to write the following:

此处不需要使用等价运算符==bool只能采用TrueFalse值。 编写以下代码就足够了:

This way of performing an if statement with a boolean requires less code and is simpler, so PEP 8 encourages it.

用布尔值执行if语句的这种方式需要更少的代码并且更简单,因此PEP 8鼓励这样做。

Use the fact that empty sequences are falsy in if statements. If you want to check whether a list is empty, you might be tempted to check the length of the list. If the list is empty, it’s length is 0 which is equivalent to False when used in an if statement. Here’s an example:

if语句中使用空序列是虚假的事实。 如果要检查列表是否为空,则可能会想检查列表的长度。 如果列表为空,则长度为0 ,在if语句中使用时等于False 。 这是一个例子:

 # Not recommended
# Not recommended
my_list my_list = = []
[]
if if not not lenlen (( my_listmy_list ):
    ):
    printprint (( 'List is empty!''List is empty!' )
)

However, in Python any empty list, string, or tuple is falsy. We can therefore come up with a simpler alternative to the above:

但是,在Python中,任何空列表,字符串或元组都是falsy 。 因此,我们可以为上述方案提供一个更简单的选择:

While both examples will print out List is empty!, the second option is simpler, so PEP 8 encourages it.

虽然两个示例都将打印输出,但List is empty! ,第二个选项更简单,因此PEP 8鼓励使用。

Use is not rather than not ... is in if statements. If you are trying to check whether a variable has a defined value, there are two options. The first is to evaluate an if statement with x is not None, as in the example below:

if语句中使用is not不是not ... is 如果要检查变量是否具有定义的值,则有两个选项。 首先是评估x is not Noneif语句x is not None ,如下例所示:

 # Recommended
# Recommended
if if x x is is not not NoneNone :
    :
    return return 'x exists!'
'x exists!'

A second option would be to evaluate x is None and then have an if statement based on not the outcome:

第二种选择是将x is None评估x is None ,然后有一个基于not结果的if语句:

While both options will be evaluated correctly, the first is simpler, so PEP 8 encourages it.

虽然两个选项都可以正确评估,但第一个选项更简单,因此PEP 8鼓励使用。

Don’t use if x: when you mean if x is not None:. Sometimes, you may have a function with arguments that are None by default. A common mistake when checking if such an argument, arg, has been given a different value is to use the following:

if x is not None:等于if x is not None:时,请不要使用if x: if x is not None: 有时,您的函数可能带有默认情况下为None的参数。 检查此类参数arg是否具有不同值时的常见错误是使用以下命令:

 # Not Recommended
# Not Recommended
if if argarg :
    :
    # Do something with arg...
# Do something with arg...

This code checks that arg is truthy. Instead, you want to check that arg is not None, so it would be better to use the following:

此代码检查arg是否为真。 相反,您要检查arg是否not None ,所以最好使用以下命令:

The mistake being made here is assuming that not None and truthy are equivalent. You could have set arg = []. As we saw above, empty lists are evaluated as falsy in Python. So, even though the argument arg has been assigned, the condition is not met, and so the code in the body of the if statement will not be executed.

此处所犯的错误是假定not None与真实是等效的。 您可以设置arg = [] 。 正如我们在上面看到的,空列表在Python中被评估为虚假。 因此,即使已分配了参数arg ,也不满足条件,因此if语句主体中的代码将不会执行。

Use .startswith() and .endswith() instead of slicing. If you were trying to check if a string word was prefixed, or suffixed, with the word cat, it might seem sensible to use list slicing. However, list slicing is prone to error, and you have to hardcode the number of characters in the prefix or suffix. It is also not clear to someone less familiar with Python list slicing what you are trying to achieve:

使用.startswith().endswith()而不是切片。 如果您要检查字符串word是否以cat前缀或后缀,则使用列表切片似乎很明智。 但是,列表切片很容易出错,并且您必须对前缀或后缀中的字符数进行硬编码。 对于不太熟悉Python列表的人,您也很难对要实现的目标进行切片:

 # Not recommended
# Not recommended
if if wordword [:[: 33 ] ] == == 'cat''cat' :
    :
    printprint (( 'The word starts with "cat"''The word starts with "cat"' )
)

However, this is not as readable as using .startswith():

但是,这不像使用.startswith()那样可读:

Similarly, the same principle applies when you’re checking for suffixes. The example below outlines how you might check whether a string ends in .jpg:

同样,检查后缀时,也应遵循相同的原则。 下面的示例概述了如何检查字符串是否以.jpg结尾:

 # Not recommended
# Not recommended
if if file_namefile_name [[ -- 33 :] :] == == 'jpg''jpg' :
    :
    printprint (( 'The file is a JPEG''The file is a JPEG' )
)

While the outcome is correct, the notation is a bit clunky and hard to read. Instead, you could use .endswith() as in the example below:

虽然结果是正确的,但该符号有点笨拙且难以阅读。 相反,您可以使用.endswith() ,如以下示例所示:

As with most of these programming recommendations, the goal is readability and simplicity. In Python, there are many different ways to perform the same action, so guidelines on which methods to chose are helpful.

与大多数编程建议一样,目标是可读性和简单性。 在Python中,执行相同操作的方式有很多,因此有关选择哪种方法的指南会有所帮助。

何时忽略PEP 8 (When to Ignore PEP 8)

The short answer to this question is never. If you follow PEP 8 to the letter, you can guarantee that you’ll have clean, professional, and readable code. This will benefit you as well as collaborators and potential employers.

这个问题的简短答案永远不会。 如果您按照字母PEP 8进行操作,则可以保证您使用的是干净,专业和易读的代码。 这将使您以及合作者和潜在的雇主受益。

However, some guidelines in PEP 8 are inconvenient in the following instances:

但是,在以下情况下,PEP 8中的一些准则不方便:

  • If complying with PEP 8 would break compatibility with existing software
  • If code surrounding what you’re working on is inconsistent with PEP 8
  • If code needs to remain compatible with older versions of Python
  • 如果遵守PEP 8,将破坏与现有软件的兼容性
  • 如果围绕您正在处理的内容的代码与PEP 8不一致
  • 如果代码需要与旧版本的Python保持兼容

帮助确保您的代码遵循PEP 8的提示和技巧 (Tips and Tricks to Help Ensure Your Code Follows PEP 8)

There is a lot to remember to make sure your code is PEP 8 compliant. It can be a tall order to remember all these rules when you’re developing code. It’s particularly time consuming to update past projects to be PEP 8 compliant. Luckily, there are tools that can help speed up this process. There are two classes of tools that you can use to enforce PEP 8 compliance: linters and autoformatters.

要确保您的代码符合PEP 8,有很多要记住的事情。 在开发代码时记住所有这些规则可能是一个很高的要求。 将过去的项目更新为符合PEP 8尤其耗时。 幸运的是,有一些工具可以帮助加快这一过程。 您可以使用两类工具来强制符合PEP 8:短绒和自动格式化程序。

短绒 (Linters)

Linters are programs that analyze code and flag errors. They provide suggestions on how to fix the error. Linters are particularly useful when installed as extensions to your text editor, as they flag errors and stylistic problems while you write. In this section, you’ll see an outline of how the linters work, with links to the text editor extensions at the end.

Linter是用于分析代码和标记错误的程序。 他们提供有关如何纠正错误的建议。 当作为文本编辑器的扩展安装时,Linter特别有用,因为它们会在您编写时标记错误和样式问题。 在本节中,您将看到短毛绒工作原理的概述,最后带有指向文本编辑器扩展的链接。

The best linters for Python code are the following:

适用于Python代码的最好的linter如下:

  • pycodestyle is a tool to check your Python code against some of the style conventions in PEP 8.

    Install pycodestyle using pip:

    $ pip install pycodestyle
    
    

    You can run pycodestyle from the terminal using the following command:

  • flake8 is a tool that combines a debugger, pyflakes, with pycodestyle.

    Install flake8 using pip:

    $ pip install flake8
    
    

    Run flake8 from the terminal using the following command:

    An example of the output is also shown.

  • pycodestyle是用于根据PEP 8中的某些样式约定检查Python代码的工具。

    使用pip安装pycodestyle

     $ pip install pycodestyle
    

    您可以使用以下命令从终端运行pycodestyle

  • flake8是将调试器pyflakespycodestyle结合在一起的工具。

    使用pip安装flake8

     $ pip install flake8
    

    使用以下命令从终端运行flake8

    还显示了输出示例。

Note: The extra line of output indicates a syntax error.

注意 :输出的额外行表示语法错误。

These are also available as extensions for Atom, Sublime Text, Visual Studio Code, and VIM. You can also find guides on setting up Sublime Text and VIM for Python development, as well as an overview of some popular text editors at RealPython.

这些还可以作为AtomSublime TextVisual Studio CodeVIM的扩展。 您还可以在RealPython上找到有关为Python开发设置Sublime TextVIM的指南,以及一些流行的文本编辑器的概述。

自动格式化程序 (Autoformatters)

Autoformatters are programs that refactor your code to conform with PEP 8 automatically. Once such program is black, which autoformats code following most of the rules in PEP 8. One big difference is that it limits line length to 88 characters, rather than 79. However, you can overwrite this by adding a command line flag, as you’ll see in an example below.

自动格式化程序是可重构代码以自动符合PEP 8的程序。 一旦此类程序为black ,它将按照PEP 8中的大多数规则自动格式化代码。最大的不同是,它将行长度限制为88个字符,而不是79个字符。不过,您可以通过添加命令行标志来覆盖它在下面的示例中将会看到。

Install black using pip. It requires Python 3.6+ to run:

使用pip安装black 。 它需要Python 3.6+才能运行:

 $ pip install black
$ pip install black

It can be run via the command line, as with the linters. Let’s say you start with the following code that isn’t PEP 8 compliant in a file called code.py:

与linters一样,它可以通过命令行运行。 假设您在名为code.py的文件中从以下与PEP 8不兼容的代码开始:

You can then run the following command via the command line:

然后,您可以通过命令行运行以下命令:

 $ black code.py
$ black code.py
reformatted code.py
reformatted code.py
All done! ✨ 🍰 ✨
All done! ✨ 🍰 ✨

code.py will be automatically reformatted to look like this:

code.py将自动重新格式化,如下所示:

If you want to alter the line length limit, then you can use the --line-length flag:

如果要更改--line-length限制,则可以使用--line-length标志:

 $ black --line-length$ black --line-length == 79 code.py
79 code.py
reformatted code.py
reformatted code.py
All done! ✨ 🍰 ✨
All done! ✨ 🍰 ✨

Two other autoformatters, autopep8 and yapf, perform actions that are similar to what black does.

其他两个自动格式化程序autopep8yapf执行的操作与black相似。

Another Real Python tutorial, Python Code Quality: Tools & Best Practices by Alexander van Tol, gives a thorough explanation of how to use these tools.

另一本Real Python教程,Alexander van Tol撰写的Python代码质量:工具和最佳实践 ,对如何使用这些工具进行了详尽的解释。

结论 (Conclusion)

You now know how to write high-quality, readable Python code by using the guidelines laid out in PEP 8. While the guidelines can seem pedantic, following them can really improve your code, especially when it comes to sharing your code with potential employers or collaborators.

现在,您知道如何通过使用PEP 8中列出的准则来编写高质量,可读性强的Python代码。尽管准则看起来有些古怪,但遵循这些准则确实可以改善您的代码,尤其是在与潜在雇主或他人共享代码时合作者。

In this tutorial, you learned:

在本教程中,您了解了:

  • What PEP 8 is and why it exists
  • Why you should aim to write PEP 8 compliant code
  • How to write code that is PEP 8 compliant
  • PEP 8是什么以及为什么存在
  • 为什么要瞄准编写符合PEP 8的代码
  • 如何编写符合PEP 8的代码

On top of all this, you also saw how to use linters and autoformatters to check your code against PEP 8 guidelines.

最重要的是,您还了解了如何使用Linters和自动格式化程序根据PEP 8准则检查代码。

If you want to learn more about PEP 8, then you can read the full documentation, or visit pep8.org, which contains the same information but has been nicely formatted. In these documents, you will find the rest of the PEP 8 guidelines not covered in this tutorial.

如果您想了解有关PEP 8的更多信息,则可以阅读完整的文档 ,或访问pep8.org ,该文档包含相同的信息,但格式正确。 在这些文档中,您将找到本教程未涵盖的PEP 8指南的其余部分。

翻译自: https://www.pybloggers.com/2018/12/how-to-write-beautiful-python-code-with-pep-8/

python pep 8

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值