1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > python代码风格指南_记录Python代码:完整指南

python代码风格指南_记录Python代码:完整指南

时间:2024-02-24 04:26:34

相关推荐

python代码风格指南_记录Python代码:完整指南

python代码风格指南

Welcome to your complete guide to documenting Python code. Whether you’re documenting a small script or a large project, whether you’re a beginner or seasoned Pythonista, this guide will cover everything you need to know.

欢迎使用完整的Python文档编写指南。 无论您是在记录小型脚本还是大型项目,无论您是初学者还是经验丰富的Pythonista,本指南都将涵盖您需要了解的所有内容。

We’ve broken up this tutorial into four major sections:

我们将本教程分为四个主要部分:

Why Documenting Your Code Is So Important:An introduction to documentation and its importanceCommenting vs. Documenting Code:An overview of the major differences between commenting and documenting, as well as the appropriate times and ways to use commentingDocumenting Your Python Code Base Using Docstrings:A deep dive into docstrings for classes, class methods, functions, modules, packages, and scripts, as well as what should be found within each oneDocumenting Your Python Projects:The necessary elements and what they should contain for your Python projects为什么编写代码如此重要 :文档简介及其重要性注释与记录代码 :注释与记录之间的主要区别的概述,以及使用注释的适当时间和方式使用Docstrings记录您的Python代码库 :深入研究类,类方法,函数,模块,包和脚本的docstring,以及每个字符串中应包含的内容记录您的Python项目 : Python项目的必要元素及其应包含的内容

Feel free to read through this tutorial from beginning to end or jump to a section you’re interested in. It was designed to work both ways.

随意从头至尾通读本教程,或跳到您感兴趣的部分。它旨在双向使用。

为什么记录代码如此重要 (Why Documenting Your Code Is So Important)

Hopefully, if you’re reading this tutorial, you already know the importance of documenting your code. But if not, then let me quote something Guido mentioned to me at a recent PyCon:

希望,如果您正在阅读本教程,那么您已经知道记录代码的重要性。 但是,如果没有,那么请允许我引用最近在PyCon上Guido提到的一些事情:

“Code is more often read than executed.”

“代码经常被读取而不是被执行。”

— Guido Van Rossum

- Guido Van Rossum

When you write code, you write it for two primary audiences: your users and your developers (including yourself). Both audiences are equally important. If you’re like me, you’ve probably opened up old codebases and wondered to yourself, “What in the world was I thinking?” If you’re having a problem reading your own code, imagine what your users or other developers are experiencing when they’re trying to use or contribute to your code.

编写代码时,是为两个主要受众编写的:用户和开发人员(包括您自己)。 两位观众同等重要。 如果您像我一样,您可能已经打开了旧的代码库,并对自己说:“我在想什么?” 如果您在阅读自己的代码时遇到问题,请想象一下您的用户或其他开发人员在尝试使用或为您的代码做贡献时会遇到什么。

Conversely, I’m sure you’ve run into a situation where you wanted to do something in Python and found what looks like a great library that can get the job done. However, when you start using the library, you look for examples, write-ups, or even official documentation on how to do something specific and can’t immediately find the solution.

相反,我确定您遇到了想要在Python中执行某些操作的情况,并发现了看起来很不错的库,可以完成工作。 但是,当您开始使用该库时,您会发现有关如何执行特定操作的示例,文章或什至官方文档,而无法立即找到解决方案。

After searching, you come to realize that the documentation is lacking or even worse, missing entirely. This is a frustrating feeling that deters you from using the library, no matter how great or efficient the code is. Daniele Procida summarized this situation best:

搜索之后,您会发现文档完全缺乏,甚至更糟。 这种令人沮丧的感觉使您无法使用库,无论代码多么出色或多么高效。 Daniele Procida最好地总结了这种情况:

“It doesn’t matter how good your software is, becauseif the documentation is not good enough, people will not use it.

“软件的好坏并不重要,因为如果文档不够好,人们将不会使用它。

— Daniele Procida

— 丹妮尔·普罗奇达

In this guide, you’ll learn from the ground up how to properly document your Python code from the smallest of scripts to the largest of Python projects to help prevent your users from ever feeling too frustrated to use or contribute to your project.

在本指南中,您将从头开始学习如何正确地记录从最小的脚本到最大的Python项目的Python代码,以帮助防止用户感到沮丧而无法使用或为您的项目做贡献。

注释与记录代码 (Commenting vs. Documenting Code)

Before we can go into how to document your Python code, we need to distinguish documenting from commenting.

在开始研究如何记录Python代码之前,我们需要将记录与注释区分开。

In general, commenting is describing your code to/for developers. The intended main audience is the maintainers and developers of the Python code. In conjunction with well-written code, comments help to guide the reader to better understand your code and its purpose and design:

通常,注释是向开发人员/为开发人员描述您的代码。 预期的主要读者是Python代码的维护者和开发者。 注释与编写良好的代码结合在一起,有助于引导读者更好地理解您的代码及其用途和设计:

“Code tells you how; Comments tell you why.”

“代码告诉您如何; 评论告诉您原因。”

— Jeff Atwood (aka Coding Horror)

- 杰夫·阿特伍德 (又名编码恐怖片)

Documenting code is describing its use and functionality to your users. While it may be helpful in the development process, the main intended audience is the users. The following section describes how and when to comment your code.

文档代码正在向用户描述其用法和功能。 尽管这可能对开发过程有所帮助,但主要的目标受众是用户。 以下部分描述了如何以及何时注释您的代码。

注释代码的基础 (Basics of Commenting Code)

Comments are created in Python using the pound sign (#) and should be brief statements no longer than a few sentences. Here’s a simple example:

注释是在Python中使用井号(#)创建的,并且应该是简短的陈述,且不得超过几句话。 这是一个简单的例子:

def def hello_worldhello_world ():():# A simple comment preceding a simple print statement# A simple comment preceding a simple print statementprintprint (( "Hello World""Hello World" ))

According to PEP 8, comments should have a maximum length of 72 characters. This is true even if your project changes the max line length to be greater than the recommended 80 characters. If a comment is going to be greater than the comment char limit, using multiple lines for the comment is appropriate:

根据PEP 8 ,注释的最大长度为72个字符。 即使您的项目将最大行长更改为大于建议的80个字符,这也是正确的。 如果注释将大于注释字符数限制,则对注释使用多行是合适的:

Commenting your code serves multiple purposes, including:

注释您的代码有多种用途,包括 :

Planning and Reviewing:When you are developing new portions of your code, it may be appropriate to first use comments as a way of planning or outlining that section of code. Remember to remove these comments once the actual coding has been implemented and reviewed/tested:

# First step# Second step# Third step

Code Description:Comments can be used to explain the intent of specific sections of code:

Algorithmic Description:When algorithms are used, especially complicated ones, it can be useful to explain how the algorithm works or how it’s implemented within your code. It may also be appropriate to describe why a specific algorithm was selected over another.

# Using quick sort for performance gains

Tagging:The use of tagging can be used to label specific sections of code where known issues or areas of improvement are located. Some examples are:BUG,FIXME, andTODO.

计划和审查:在开发代码的新部分时,首先使用注释作为计划或概述代码部分的一种方式可能是适当的。 记住,一旦实现并审查/测试了实际编码,请删除这些注释:

# First step# Second step# Third step

代码说明:注释可用于解释代码特定部分的意图:

算法说明:当使用算法时,尤其是复杂算法时,解释算法如何工作或如何在代码中实现将很有用。 描述为什么选择特定算法而不是另一个算法也可能是适当的。

# Using quick sort for performance gains

标记:使用标记可以标记已知问题或需要改进的地方的特定代码部分。 一些示例是:BUGFIXMETODO

Comments to your code should be kept brief and focused. Avoid using long comments when possible. Additionally, you should use the following four essential rules as suggested by Jeff Atwood:

对代码的注释应保持简短且重点突出。 尽可能避免使用长注释。 此外,您应使用Jeff Atwood建议的以下四个基本规则:

Keep comments as close to the code being described as possible. Comments that aren’t near their describing code are frustrating to the reader and easily missed when updates are made.

Don’t use complex formatting (such as tables or ASCII figures). Complex formatting leads to distracting content and can be difficult to maintain over time.

Don’t include redundant information. Assume the reader of the code has a basic understanding of programming principles and language syntax.

Design your code to comment itself. The easiest way to understand code is by reading it. When you design your code using clear, easy-to-understand concepts, the reader will be able to quickly conceptualize your intent.

注释应尽可能靠近所描述的代码。 与描述代码不符的注释会使读者感到沮丧,并且在进行更新时很容易错过。

不要使用复杂的格式(例如表格或ASCII数字)。 复杂的格式会导致内容分散注意力,并且随着时间的推移可能难以维护。

不要包含多余的信息。 假定代码的读者对编程原理和语言语法有基本的了解。

设计代码以对其进行注释。 理解代码的最简单方法是阅读代码。 当您使用清晰,易于理解的概念设计代码时,读者将能够快速将您的意图概念化。

Remember that comments are designed for the reader, including yourself, to help guide them in understanding the purpose and design of the software.

请记住,注释是为包括您自己在内的读者设计的,以帮助指导他们理解软件的目的和设计。

通过类型提示注释代码(Python 3.5+) (Commenting Code via Type Hinting (Python 3.5+))

Type hinting was added to Python 3.5 and is an additional form to help the readers of your code. In fact, it takes Jeff’s fourth suggestion from above to the next level. It allows the developer to design and explain portions of their code without commenting. Here’s a quick example:

类型提示已添加到Python 3.5中,是帮助您的代码读者的另一种形式。 实际上,这将Jeff的第四个建议从上到下。 它允许开发人员设计和解释部分代码而无需评论。 这是一个简单的例子:

def def hello_namehello_name (( namename : : strstr ) ) -> -> strstr ::returnreturn (( ff "Hello "Hello {name}{name} "" ))

From examining the type hinting, you can immediately tell that the function expects the inputnameto be of a typestr, or string. You can also tell that the expected output of the function will be of a typestr, or string, as well. While type hinting helps reduce comments, take into consideration that doing so may also make extra work when you are creating or updating your project documentation.

通过检查类型提示,您可以立即知道该函数期望输入name的类型为str或字符串。 您还可以告诉您,该函数的预期输出也将为str或string类型。 尽管类型提示有助于减少注释,但要考虑到这样做可能还会在创建或更新项目文档时带来额外的工作。

You can learn more about type hinting and type checking from this video created by Dan Bader.

您可以从Dan Bader创作的视频中了解有关类型提示和类型检查的更多信息。

使用文档字符串记录Python代码库 (Documenting Your Python Code Base Using Docstrings)

Now that we’ve learned about commenting, let’s take a deep dive into documenting a Python code base. In this section, you’ll learn about docstrings and how to use them for documentation. This section is further divided into the following sub-sections:

既然我们已经了解了注释,那么让我们深入研究一下记录Python代码库的过程。 在本节中,您将学习文档字符串以及如何将其用于文档编制。 本节进一步分为以下小节:

Docstrings Background:A background on how docstrings work internally within PythonDocstring Types:The various docstring “types” (function, class, class method, module, package, and script)Docstring Formats:The different docstring “formats” (Google, NumPy/SciPy, reStructured Text, and Epytext) 文档字符串背景 :有关文档字符串如何在Python内部进行工作的背景 文档字符串类型 :各种文档字符串“类型”(函数,类,类方法,模块,包和脚本) 文档字符串格式 :不同的文档字符串“格式”(Google,NumPy / SciPy,重组文本和Epytext)

Docstrings背景 (Docstrings Background)

Documenting your Python code is all centered on docstrings. These are built-in strings that, when configured correctly, can help your users and yourself with your project’s documentation. Along with docstrings, Python also has the built-in functionhelp()that prints out the objects docstring to the console. Here’s a quick example:

记录Python代码全都以文档字符串为中心。 这些是内置字符串,如果配置正确,则可以帮助您的用户和您自己使用项目的文档。 除了文档字符串,Python还具有内置函数help(),可将对象文档字符串输出到控制台。 这是一个简单的例子:

How is this output generated? Since everything in Python is an object, you can examine the directory of the object using thedir()command. Let’s do that and see what find:

如何产生此输出? 由于Python中的所有内容都是对象,因此您可以使用dir()命令检查对象的dir()。 让我们这样做,看看有什么发现:

>>> >>> dirdir (( strstr ))['__add__', ..., '__doc__', ..., 'zfill'] # Truncated for readability['__add__', ..., '__doc__', ..., 'zfill'] # Truncated for readability

Within that directory output, there’s an interesting property,__doc__. If you examine that property, you’ll discover this:

在该目录输出中,有一个有趣的属性__doc__。 如果检查该属性,则会发现以下内容:

Voilà! You’ve found where docstrings are stored within the object. This means that you can directly manipulate that property. However, there are restrictions for builtins:

瞧! 您已找到文档字符串存储在对象中的位置。 这意味着您可以直接操纵该属性。 但是,内置函数有一些限制:

>>> >>> strstr .. __doc__ __doc__ = = "I'm a little string doc! Short and stout; here is my input and print me for my out""I'm a little string doc! Short and stout; here is my input and print me for my out"Traceback (most recent call last):File Traceback (most recent call last):File "<stdin>", line "<stdin>" , line 1, in 1 , in <module><module>TypeError: TypeError : can't set attributes of built-in/extension type 'str'can't set attributes of built-in/extension type 'str'

Any other custom object can be manipulated:

任何其他自定义对象都可以操作:

>>> >>> helphelp (( say_hellosay_hello ))Help on function say_hello in module __main__:Help on function say_hello in module __main__:say_hello(name)say_hello(name) A simple function that says hello... Richie style A simple function that says hello... Richie style

Python has one more feature that simplifies docstring creation. Instead of directly manipulating the__doc__property, the strategic placement of the string literal directly below the object will automatically set the__doc__value. Here’s what happens with the same example as above:

Python的另一项功能可以简化文档字符串的创建。 代替直接操作__doc__属性,直接将字符串文字放在对象下面的策略位置将自动设置__doc__值。 与上述相同的示例将发生以下情况:

>>> >>> helphelp (( say_hellosay_hello ))Help on function say_hello in module __main__:Help on function say_hello in module __main__:say_hello(name)say_hello(name) A simple function that says hello... Richie style A simple function that says hello... Richie style

There you go! Now you understand the background of docstrings. Now it’s time to learn about the different types of docstrings and what information they should contain.

你去! 现在您了解了文档字符串的背景。 现在是时候学习不同类型的文档字符串以及它们应包含的信息。

Docstring类型 (Docstring Types)

Docstring conventions are described within PEP 257. Their purpose is to provide your users with a brief overview of the object. They should be kept concise enough to be easy to maintain but still be elaborate enough for new users to understand their purpose and how to use the documented object.

文档字符串约定在PEP 257中进行了描述。 他们的目的是为您的用户提供对象的简要概述。 它们应该保持简洁,以便于维护,但又要足够复杂,以使新用户了解他们的目的以及如何使用记录的对象。

In all cases, the docstrings should use the triple-double quote (""") string format. This should be done whether the docstring is multi-lined or not. At a bare minimum, a docstring should be a quick summary of whatever is it you’re describing and should be contained within a single line:

在所有情况下,文档字符串都应使用三重双引号(""")字符串格式。无论文档​​字符串是否为多行,都应这样做。至少,文档字符串应是任何内容的快速摘要。您要描述的内容,应包含在一行中:

Multi-lined docstrings are used to further elaborate on the object beyond the summary. All multi-lined docstrings have the following parts:

除摘要外,多行文档字符串用于进一步详细说明对象。 所有多行文档字符串均包含以下部分:

A one-line summary lineA blank line proceeding the summaryAny further elaboration for the docstringAnother blank line 单行摘要行 进行摘要的空白行 对文档字符串的任何进一步说明 另一个空白行

"""This is the summary line"""This is the summary lineThis is the further elaboration of the docstring. Within this section,This is the further elaboration of the docstring. Within this section,you can elaborate further on details as appropriate for the situation.you can elaborate further on details as appropriate for the situation.Notice that the summary and the elaboration is separated by a blank newNotice that the summary and the elaboration is separated by a blank newline.line.""""""# Notice the blank line above. Code should continue on this line.# Notice the blank line above. Code should continue on this line.

All docstrings should have the same max character length as comments (72 characters). Docstrings can be further broken up into three major categories:

所有文档字符串的最大字符长度应与注释相同(72个字符)。 文档字符串可以进一步分为三大类:

Class Docstrings:Class and class methodsPackage and Module Docstrings:Package, modules, and functionsScript Docstrings:Script and functions类文档字符串:类和类方法软件包和模块文档字符串:软件包,模块和功能脚本文档字符串:脚本和功能

类文档字符串 (Class Docstrings)

Class Docstrings are created for the class itself, as well as any class methods. The docstrings are placed immediately following the class or class method indented by one level:

将为类本身以及任何类方法创建类文档字符串。 文档字符串紧跟在紧缩一级的类或类方法之后:

Class docstrings should contain the following information:

类文档字符串应包含以下信息:

A brief summary of its purpose and behaviorAny public methods, along with a brief descriptionAny class properties (attributes)Anything related to the interface for subclassers, if the class is intended to be subclassed 其目的和行为的简要概述 任何公共方法,以及简要说明 任何类属性(属性) 与子类接口有关的任何东西(如果要将该类子类化)

The class constructor parameters should be documented within the__init__class method docstring. Individual methods should be documented using their individual docstrings. Class method docstrings should contain the following:

类构造函数的参数应记录在__init__类方法docstring中。 各个方法应使用其各自的文档字符串进行记录。 类方法文档字符串应包含以下内容:

A brief description of what the method is and what it’s used forAny arguments (both required and optional) that are passed including keyword argumentsLabel any arguments that are considered optional or have a default valueAny side effects that occur when executing the methodAny exceptions that are raisedAny restrictions on when the method can be called 关于什么是方法及其用途的简要说明 传递的所有参数(必需的和可选的),包括关键字参数 标记所有被认为是可选的或具有默认值的参数 执行该方法时发生的任何副作用 引发的任何异常 何时可以调用该方法的任何限制

Let’s take a simple example of a data class that represents an Animal. This class will contain a few class properties, instance properties, a__init__, and a single instance method:

让我们以代表动物的数据类的简单示例为例。 此类将包含一些类属性,实例属性,__init__和单个实例方法:

class class AnimalAnimal ::"""""" A class used to represent an Animal A class used to represent an Animal ... ... Attributes Attributes ---------- ---------- says_str : str says_str : str a formatted string to print out what the animal says a formatted string to print out what the animal says name : str name : str the name of the animal the name of the animal sound : str sound : str the sound that the animal makes the sound that the animal makes num_legs : int num_legs : int the number of legs the animal has (default 4) the number of legs the animal has (default 4) Methods Methods ------- ------- says(sound=None) says(sound=None) Prints the animals name and what sound it makes Prints the animals name and what sound it makes """ """says_str says_str = = "A "A {name}{name} says says {sound}{sound} ""def def __init____init__ (( selfself , , namename , , soundsound , , num_legsnum_legs ):):"""""" Parameters Parameters ---------- ---------- name : str name : str The name of the animal The name of the animal sound : str sound : str The sound the animal makes The sound the animal makes num_legs : int, optional num_legs : int, optional The number of legs the animal (default is 4) The number of legs the animal (default is 4) """ """selfself .. name name = = namenameselfself .. sound sound = = soundsoundselfself .. num_legs num_legs = = num_legsnum_legsdef def sayssays (( selfself , , soundsound == NoneNone ):):"""Prints what the animals name is and what sound it makes."""Prints what the animals name is and what sound it makes. If the argument `sound` isn't passed in, the default Animal If the argument `sound` isn't passed in, the default Animal sound is used. sound is used. Parameters Parameters ---------- ---------- sound : str, optional sound : str, optional The sound the animal makes (default is None) The sound the animal makes (default is None) Raises Raises ------ ------ NotImplementedError NotImplementedError If no sound is set for the animal or passed in as a If no sound is set for the animal or passed in as a parameter. parameter. """ """if if selfself .. sound sound is is None None and and sound sound is is NoneNone ::raise raise NotImplementedErrorNotImplementedError (( "Silent Animals are not supported!""Silent Animals are not supported!" ))out_sound out_sound = = selfself .. sound sound if if sound sound is is None None else else soundsoundprintprint (( selfself .. says_strsays_str .. formatformat (( namename == selfself .. namename , , soundsound == out_soundout_sound ))))

软件包和模块文档字符串 (Package and Module Docstrings)

Package docstrings should be placed at the top of the package’s__init__.pyfile. This docstring should list the modules and sub-packages that are exported by the package.

程序包文档字符串应放在程序包的__init__.py文件的顶部。 此文档字符串应列出软件包导出的模块和子软件包。

Module docstrings are similar to class docstrings. Instead of classes and class methods being documented, it’s now the module and any functions found within. Module docstrings are placed at the top of the file even before any imports. Module docstrings should include the following:

模块文档字符串类似于类文档字符串。 现在不再是文件类和类方法的文档了,而是模块和其中的任何函数。 模块文档字符串甚至在任何导入之前都放置在文件的顶部。 模块文档字符串应包括以下内容:

A brief description of the module and its purposeA list of any classes, exception, functions, and any other objects exported by the module 模块及其用途的简要说明 模块导出的所有类,异常,函数和任何其他对象的列表

The docstring for a module function should include the same items as a class method:

模块函数的文档字符串应包含与类方法相同的项目:

A brief description of what the function is and what it’s used forAny arguments (both required and optional) that are passed including keyword argumentsLabel any arguments that are considered optionalAny side effects that occur when executing the functionAny exceptions that are raisedAny restrictions on when the function can be called 功能简介及其用途的简要说明 传递的所有参数(必需的和可选的),包括关键字参数 标记所有被视为可选的参数 执行功能时发生的任何副作用 引发的任何异常 关于何时可以调用该函数的任何限制

脚本文档字符串 (Script Docstrings)

Scripts are considered to be single file executables run from the console. Docstrings for scripts are placed at the top of the file and should be documented well enough for users to be able to have a sufficient understanding of how to use the script. It should be usable for its “usage” message, when the user incorrectly passes in a parameter or uses the-hoption.

脚本被视为从控制台运行的单个文件可执行文件。 脚本的文档字符串放在文件的顶部,并且应该被充分记录,以使用户能够充分了解如何使用脚本。 当用户错误地传递参数或使用-h选项时,它应可用于其“使用情况”消息。

If you useargparse, then you can omit parameter-specific documentation, assuming it’s correctly been documented within thehelpparameter of theargparser.parser.add_argumentfunction. It is recommended to use the__doc__for thedescriptionparameter withinargparse.ArgumentReader’s constructor. Check out our tutorial on Command-Line Parsing Libraries for more details on how to useargparseand other common command line parsers.

如果您使用argparse,则可以忽略特定于参数的文档,前提是已在argparser.parser.add_argument函数的help参数中正确记录了该文档。 建议在argparse.ArgumentReader的构造函数内对description参数使用__doc__。 查看我们的命令行解析库教程,以获取有关如何使用argparse和其他常见命令行解析器的更多详细信息。

Finally, any custom or third-party imports should be listed within the docstrings to allow users to know which packages may be required for running the script. Here’s an example of a script that is used to simply print out the column headers of a spreadsheet:

最后,任何自定义导入或第三方导入都应在文档字符串中列出,以使用户知道运行脚本可能需要哪些软件包。 这是一个脚本示例,用于简单地打印出电子表格的列标题:

Docstring格式 (Docstring Formats)

You may have noticed that, throughout the examples given in this tutorial, there has been specific formatting with common elements:Arguments,Returns, andAttributes. There are specific docstrings formats that can be used to help docstring parsers and users have a familiar and known format. The formatting used within the examples in this tutorial are NumPy/SciPy-style docstrings. Some of the most common formats are the following:

您可能已经注意到,在本教程中给出的所有示例中,都存在带有常见元素(ArgumentsReturnsAttributes特定格式。 有特定的文档字符串格式可用于帮助文档字符串解析器,并且用户具有熟悉和已知的格式。 本教程示例中使用的格式为NumPy / SciPy样式的文档字符串。 一些最常见的格式如下:

The selection of the docstring format is up to you, but you should stick with the same format throughout your document/project. The following are examples of each type to give you an idea of how each documentation format looks.

文档字符串格式的选择取决于您,但是在整个文档/项目中,您都应坚持使用相同的格式。 以下是每种类型的示例,以使您了解每种文档格式的外观。

Google Docstrings示例 (Google Docstrings Example)

"""Gets and prints the spreadsheet's header columns"""Gets and prints the spreadsheet's header columnsParameters:Parameters: file_loc (str): The file location of the spreadsheet file_loc (str): The file location of the spreadsheet print_cols (bool): A flag used to print the columns to the console print_cols (bool): A flag used to print the columns to the console (default is False) (default is False)Returns:Returns: list: a list of strings representing the header columns list: a list of strings representing the header columns""""""

重组文本示例 (reStructured Text Example)

NumPy / SciPy文档字符串示例 (NumPy/SciPy Docstrings Example)

"""Gets and prints the spreadsheet's header columns"""Gets and prints the spreadsheet's header columnsParametersParameters--------------------file_loc : strfile_loc : str The file location of the spreadsheet The file location of the spreadsheetprint_cols : bool, optionalprint_cols : bool, optional A flag used to print the columns to the console (default is False) A flag used to print the columns to the console (default is False)ReturnsReturns--------------listlist a list of strings representing the header columns a list of strings representing the header columns""""""

Epytext示例 (Epytext Example)

记录您的Python项目 (Documenting Your Python Projects)

Python projects come in all sorts of shapes, sizes, and purposes. The way you document your project should suit your specific situation. Keep in mind who the users of your project are going to be and adapt to their needs. Depending on the project type, certain aspects of documentation are recommended. The general layout of the project and its documentation should be as follows:

Python项目具有各种形状,大小和用途。 您记录项目的方式应适合您的具体情况。 请记住您的项目的用户将是谁,并适应他们的需求。 根据项目类型,建议文档的某些方面。 项目的总体布局及其文档应如下所示:

project_root/│├── project/ # Project source code├── docs/├── README├── HOW_TO_CONTRIBUTE├── CODE_OF_CONDUCT├── examples.pyproject_root/│├── project/ # Project source code├── docs/├── README├── HOW_TO_CONTRIBUTE├── CODE_OF_CONDUCT├── examples.py

Projects can be generally subdivided into three major types: Private, Shared, and Public/Open Source.

项目通常可以分为三种主要类型:私有,共享和公共/开源。

私人项目 (Private Projects)

Private projects are projects intended for personal use only and generally aren’t shared with other users or developers. Documentation can be pretty light on these types of projects. There are some recommended parts to add as needed:

私人项目是仅供个人使用的项目,通常不会与其他用户或开发人员共享。 这些类型的项目的文档可能很少。 根据需要添加一些建议的部分:

Readme:A brief summary of the project and its purpose. Include any special requirements for installation or operating the project.examples.py:A Python script file that gives simple examples of how to use the project.自述文件:项目及其目的的简短摘要。 包括安装或运行项目的任何特殊要求。examples.py一个Python脚本文件,提供了有关如何使用该项目的简单示例。

Remember, even though private projects are intended for you personally, you are also considered a user. Think about anything that may be confusing to you down the road and make sure to capture those in either comments, docstrings, or the readme.

请记住,即使私人项目是针对您个人的,您也被视为用户。 考虑一下可能会使您困惑的任何事情,并确保将其捕获在注释,文档字符串或自述文件中。

共享项目 (Shared Projects)

Shared projects are projects in which you collaborate with a few other people in the development and/or use of the project. The “customer” or user of the project continues to be yourself and those limited few that use the project as well.

共享项目是您在开发和/或使用项目时与其他几个人协作的项目。 项目的“客户”或用户仍然是您自己,使用该项目的少数人也是如此。

Documentation should be a little more rigorous than it needs to be for a private project, mainly to help onboard new members to the project or alert contributors/users of new changes to the project. Some of the recommended parts to add to the project are the following:

文档应该比私有项目所需的文件更为严格,主要是为了帮助该项目的新成员加入或向项目提供者/用户警告项目的新更改。 建议添加到项目中的一些部分如下:

Readme:A brief summary of the project and its purpose. Include any special requirements for installing or operating the project. Additionally, add any major changes since the previous version.examples.py:A Python script file that gives simple examples of how to use the projects.How to Contribute:This should include how new contributors to the project can start contributing.自述文件:项目及其目的的简短摘要。 包括安装或运行项目的任何特殊要求。 此外,添加自先前版本以来的所有主要更改。examples.py一个Python脚本文件,提供了有关如何使用项目的简单示例。如何贡献:这应该包括项目的新贡献者如何开始贡献。

公共和开源项目 (Public and Open Source Projects)

Public and Open Source projects are projects that are intended to be shared with a large group of users and can involve large development teams. These projects should place as high of a priority on project documentation as the actual development of the project itself. Some of the recommended parts to add to the project are the following:

公共项目和开源项目是旨在与大量用户共享的项目,并且可能涉及大型开发团队。 这些项目应在项目文档中优先于项目本身的实际开发。 建议添加到项目中的一些部分如下:

Readme:A brief summary of the project and its purpose. Include any special requirements for installing or operating the projects. Additionally, add any major changes since the previous version. Finally, add links to further documentation, bug reporting, and any other important information for the project. Dan Bader has put together a great tutorial on what all should be included in your readme.

How to Contribute:This should include how new contributors to the project can help. This includes developing new features, fixing known issues, adding documentation, adding new tests, or reporting issues.

Code of Conduct:Defines how other contributors should treat each other when developing or using your software. This also states what will happen if this code is broken. If you’re using Github, a Code of Conduct template can be generated with recommended wording. For Open Source projects especially, consider adding this.

License:A plaintext file that describes the license your project is using. For Open Source projects especially, consider adding this.

docs:A folder that contains further documentation. The next section describes more fully what should be included and how to organize the contents of this folder.

自述文件:项目及其目的的简短摘要。 包括安装或运行项目的任何特殊要求。 此外,添加自先前版本以来的所有主要更改。 最后,添加指向该项目的进一步文档,错误报告以及任何其他重要信息的链接。 丹·巴德(Dan Bader)撰写了一篇很棒的教程,介绍了自述文件中应包含的所有内容。

如何贡献:应该包括新的项目贡献者如何提供帮助。 这包括开发新功能,解决已知问题,添加文档,添加新测试或报告问题。

行为准则:定义在开发或使用软件时其他贡献者应如何相互对待。 这也说明如果该代码被破坏,将会发生什么。 如果您使用的是Github,可以使用推荐的措词生成行为准则模板 。 特别是对于开源项目,请考虑添加它。

许可证:描述您的项目正在使用的许可证的纯文本文件。 特别是对于开源项目,请考虑添加它。

docs:包含更多文档的文件夹。 下一节将更全面地描述应包括的内容以及如何组织此文件夹的内容。

docs文件夹的四个主要部分 (The Four Main Sections of thedocsFolder)

Daniele Procida gave a wonderful PyCon talk and subsequent blog post about documenting Python projects. He mentions that all projects should have the following four major sections to help you focus your work:

Daniele Procida发表了精彩的PyCon 演讲 ,随后发表了有关记录Python项目的博客文章 。 他提到所有项目都应包含以下四个主要部分,以帮助您集中精力进行工作:

Tutorials: Lessons that take the reader by the hand through a series of steps to complete a projects (or meaningful exercise). Geared towards the users learning.How-To Guides: Guides that take the reader through the steps required to solve a common problem (problem-oriented recipes).References: Explanations that clarify and illuminate a particular topic. Geared towards understanding.Explanations: Technical descriptions of the machinery and how to operate it (key classes, functions, APIs, and so forth). Think Encyclopedia article.教程:这些课程将引导读者逐步完成一系列项目(或有意义的练习)。 面向用户学习。操作方法指南:指导读者完成解决常见问题所需步骤的指南(面向问题的食谱)。参考文献:阐明和阐明特定主题的解释。 面向理解。说明:机械及其操作方法的技术说明(键类,功能,API等)。 想想百科全书。

The following table shows how all of these sections relates to each other as well as their overall purpose:

下表显示了所有这些部分如何相互关联以及它们的总体目的:

In the end, you want to make sure that your users have access to the answers to any questions they may have. By organizing your project in this manner, you’ll be able to answer those questions easily and in a format they’ll be able to navigate quickly.

最后,您要确保您的用户可以访问他们可能遇到的任何问题的答案。 通过以这种方式组织项目,您将能够轻松地回答这些问题,并且格式可以使他们快速浏览。

文档工具和资源 (Documentation Tools and Resources)

Documenting your code, especially large projects, can be daunting. Thankfully there are some tools out and references to get you started:

编写代码,尤其是大型项目,可能会很艰巨。 幸运的是,有一些工具和参考资料可以帮助您入门:

Along with these tools, there are some additional tutorials, videos, and articles that can be useful when you are documenting your project:

除了这些工具以外,还有一些其他教程,视频和文章在记录项目时会很有用:

Carol Willing – Practical Sphinx – PyCon Daniele Procida – Documentation-driven development – Lessons from the Django Project – PyCon Eric Holscher – Documenting your project with Sphinx & Read the Docs – PyCon Titus Brown, Luiz Irber – Creating, building, testing, and documenting a Python project: a hands-on HOWTO – PyCon Restructured Text Official DocumentationSphinx’s reStructured Text Primer Carol Willing –实用狮身人面像– PyCon Daniele Procida –文档驱动的开发– Django项目的经验教训– PyCon Eric Holscher –使用Sphinx记录您的项目并阅读文档– PyCon Titus Brown,Luiz Irber –创建,构建,测试和记录Python项目:动手操作手册– PyCon 重组文本官方文档 Sphinx的重组文本入门

Sometimes, the best way to learn is to mimic others. Here are some great examples of projects that use documentation well:

有时,最好的学习方法是模仿他人。 这里是一些很好地使用文档的项目的好例子:

Django:Docs (Source)Requests:Docs (Source)Click:Docs (Source)Pandas:Docs (Source)Django:文档 ( 源 )请求:文档 ( 来源 )点击:文档 ( 来源 )熊猫:文件 ( 来源 )

我从哪说起呢? (Where Do I Start?)

The documentation of projects have a simple progression:

项目文档的进展很简单:

No DocumentationSome DocumentationComplete DocumentationGood DocumentationGreat Documentation 没有文件 一些文件 完整的文件 好的文件 优质文件

If you’re at a loss about where to go next with your documentation, look at where your project is now in relation to the progression above. Do you have any documentation? If not, then start there. If you have some documentation but are missing some of the key project files, get started by adding those.

如果您对下一步如何使用文档不知所措,请查看与上述进度相关的项目现在所处的位置。 你有文件吗? 如果不是,则从那里开始。 如果您有一些文档,但是缺少一些关键的项目文件,请从添加这些文件开始。

In the end, don’t get discouraged or overwhelmed by the amount of work required for documenting code. Once you get started documenting your code, it becomes easier to keep going. Feel free to comment if you have questions or reach out to the Real Python Team on social media, and we’ll help.

最后,不要因为编写代码所需的工作量而灰心或不知所措。 一旦开始编写代码文档,继续进行操作就会变得更加容易。 如果您有任何疑问或在社交媒体上与Real Python团队联系,请随时发表评论,我们会为您提供帮助。

翻译自: //07/documenting-python-code-a-complete-guide/

python代码风格指南

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。