简体   繁体   English

Python文件的常见头格式是什么?

[英]What is the common header format of Python files?

I came across the following header format for Python source files in a document about Python coding guidelines:我在有关 Python 编码指南的文档中遇到了 Python 源文件的以下标头格式:

#!/usr/bin/env python

"""Foobar.py: Description of what foobar does."""

__author__      = "Barack Obama"
__copyright__   = "Copyright 2009, Planet Earth"

Is this the standard format of headers in the Python world?这是 Python 世界中标头的标准格式吗? What other fields/information can I put in the header?我可以在标题中放入哪些其他字段/信息? Python gurus share your guidelines for good Python source headers :-) Python 大师分享您关于良好 Python 源头文件的指南:-)

Its all metadata for the Foobar module.它是Foobar模块的所有元数据。

The first one is the docstring of the module, that is already explained in Peter's answer .第一个是模块的docstring ,已在Peter's answer 中进行了解释。

How do I organize my modules (source files)? 如何组织我的模块(源文件)? (Archive) (档案)

The first line of each file shoud be #!/usr/bin/env python .每个文件的第一行应该是#!/usr/bin/env python This makes it possible to run the file as a script invoking the interpreter implicitly, eg in a CGI context.这使得可以将文件作为隐式调用解释器的脚本运行,例如在 CGI 上下文中。

Next should be the docstring with a description.接下来应该是带有描述的文档字符串。 If the description is long, the first line should be a short summary that makes sense on its own, separated from the rest by a newline.如果描述很长,第一行应该是一个简短的摘要,它本身就有意义,用换行符与其余部分分开。

All code, including import statements, should follow the docstring.所有代码,包括导入语句,都应该遵循文档字符串。 Otherwise, the docstring will not be recognized by the interpreter, and you will not have access to it in interactive sessions (ie through obj.__doc__ ) or when generating documentation with automated tools.否则,解释器将无法识别文档字符串,并且您将无法在交互式会话中(即通过obj.__doc__ )或使用自动化工具生成文档时访问它。

Import built-in modules first, followed by third-party modules, followed by any changes to the path and your own modules.首先导入内置模块,然后是第三方模块,然后是对路径和您自己的模块的任何更改。 Especially, additions to the path and names of your modules are likely to change rapidly: keeping them in one place makes them easier to find.特别是,添加到您的模块的路径和名称可能会迅速更改:将它们放在一个地方更容易找到。

Next should be authorship information.接下来应该是作者信息。 This information should follow this format:此信息应遵循以下格式:

 __author__ = "Rob Knight, Gavin Huttley, and Peter Maxwell" __copyright__ = "Copyright 2007, The Cogent Project" __credits__ = ["Rob Knight", "Peter Maxwell", "Gavin Huttley", "Matthew Wakefield"] __license__ = "GPL" __version__ = "1.0.1" __maintainer__ = "Rob Knight" __email__ = "rob@spot.colorado.edu" __status__ = "Production"

Status should typically be one of "Prototype", "Development", or "Production".状态通常应该是“原型”、“开发”或“生产”之一。 __maintainer__ should be the person who will fix bugs and make improvements if imported. __maintainer__应该是修复错误并在导入后进行改进的人。 __credits__ differs from __author__ in that __credits__ includes people who reported bug fixes, made suggestions, etc. but did not actually write the code. __credits__不同于__author____credits__包括谁报告bug修复,提出建议等,但实际上并没有写代码的人。

Here you have more information, listing __author__ , __authors__ , __contact__ , __copyright__ , __license__ , __deprecated__ , __date__ and __version__ as recognized metadata. 这里有更多信息,列出__author____authors____contact____copyright____license____deprecated____date____version__作为公认的元数据。

I strongly favour minimal file headers, by which I mean just:我强烈支持最小的文件头,我的意思是:

  • The hashbang ( #! line) if this is an executable script如果这是一个可执行脚本,则使用 hashbang( #!行)
  • Module docstring模块文档字符串
  • Imports, grouped in the standard way, eg:进口,以标准方式分组,例如:
  import os    # standard library
  import sys

  import requests  # 3rd party packages

  from mypackage import (  # local source
      mymodule,
      myothermodule,
  )

ie. IE。 three groups of imports, with a single blank line between them.三组导入,它们之间有一个空行。 Within each group, imports are sorted.在每个组中,对导入进行排序。 The final group, imports from local source, can either be absolute imports as shown, or explicit relative imports.最后一组,从本地源导入,可以是所示的绝对导入,也可以是显式相对导入。

Everything else is a waste of time, visual space, and is actively misleading.其他一切都是浪费时间和视觉空间,并且是积极误导的。

If you have legal disclaimers or licencing info, it goes into a separate file.如果您有法律免责声明或许可信息,它会进入一个单独的文件。 It does not need to infect every source code file.它不需要感染每个源代码文件。 Your copyright should be part of this.您的版权应该是其中的一部分。 People should be able to find it in your LICENSE file, not random source code.人们应该能够在您的LICENSE文件中找到它,而不是随机的源代码。

Metadata such as authorship and dates is already maintained by your source control.作者和日期等元数据已由您的源代码管理维护。 There is no need to add a less-detailed, erroneous, and out-of-date version of the same info in the file itself.无需在文件本身中添加相同信息的不太详细、错误和过时的版本。

I don't believe there is any other data that everyone needs to put into all their source files.我不相信每个人都需要将任何其他数据放入他们的所有源文件中。 You may have some particular requirement to do so, but such things apply, by definition, only to you.您可能有一些特殊的要求这样做,但根据定义,这些事情只适用于您。 They have no place in “general headers recommended for everyone”.它们在“推荐给所有人的通用标题”中没有位置。

The answers above are really complete, but if you want a quick and dirty header to copy'n paste, use this:上面的答案非常完整,但是如果您想要一个快速而肮脏的标题来复制粘贴,请使用以下命令:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Module documentation goes here
   and here
   and ...
"""

Why this is a good one:为什么这是一个好的:

  • The first line is for *nix users.第一行是针对 *nix 用户的。 It will choose the Python interpreter in the user path, so will automatically choose the user preferred interpreter.它将在用户路径中选择 Python 解释器,因此将自动选择用户首选的解释器。
  • The second one is the file encoding.第二个是文件编码。 Nowadays every file must have a encoding associated.现在每个文件都必须有一个相关的编码。 UTF-8 will work everywhere. UTF-8 将适用于任何地方。 Just legacy projects would use other encoding.只是遗留项目会使用其他编码。
  • And a very simple documentation.和一个非常简单的文档。 It can fill multiple lines.它可以填充多行。

See also: https://www.python.org/dev/peps/pep-0263/另见: https : //www.python.org/dev/peps/pep-0263/

If you just write a class in each file, you don't even need the documentation (it would go inside the class doc).如果您只是在每个文件中编写一个类,您甚至不需要文档(它会在类文档中)。

Also see PEP 263 if you are using a non-ascii characterset如果您使用的是非 ASCII 字符集,另请参阅PEP 263

Abstract抽象的

This PEP proposes to introduce a syntax to declare the encoding of a Python source file.此 PEP 建议引入一种语法来声明 Python 源文件的编码。 The encoding information is then used by the Python parser to interpret the file using the given encoding.然后 Python 解析器使用编码信息来解释使用给定编码的文件。 Most notably this enhances the interpretation of Unicode literals in the source code and makes it possible to write Unicode literals using eg UTF-8 directly in an Unicode aware editor.最值得注意的是,这增强了对源代码中 Unicode 文字的解释,并使直接在 Unicode 感知编辑器中使用例如 UTF-8 编写 Unicode 文字成为可能。

Problem问题

In Python 2.1, Unicode literals can only be written using the Latin-1 based encoding "unicode-escape".在 Python 2.1 中,Unicode 文字只能使用基于 Latin-1 的编码“unicode-escape”来编写。 This makes the programming environment rather unfriendly to Python users who live and work in non-Latin-1 locales such as many of the Asian countries.这使得编程环境对在非拉丁语 1 语言环境(例如许多亚洲国家/地区)中生活和工作的 Python 用户相当不友好。 Programmers can write their 8-bit strings using the favorite encoding, but are bound to the "unicode-escape" encoding for Unicode literals.程序员可以使用最喜欢的编码编写他们的 8 位字符串,但必须使用 Unicode 文字的“unicode-escape”编码。

Proposed Solution建议的解决方案

I propose to make the Python source code encoding both visible and changeable on a per-source file basis by using a special comment at the top of the file to declare the encoding.我建议通过在文件顶部使用特殊注释来声明编码,使 Python 源代码编码在每个源文件的基础上既可见又可更改。

To make Python aware of this encoding declaration a number of concept changes are necessary with respect to the handling of Python source code data.为了让 Python 知道这个编码声明,在处理 Python 源代码数据方面需要进行一些概念更改。

Defining the Encoding定义编码

Python will default to ASCII as standard encoding if no other encoding hints are given.如果没有给出其他编码提示,Python 将默认使用 ASCII 作为标准编码。

To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:要定义源代码编码,必须将魔术注释作为文件的第一行或第二行放入源文件中,例如:

 # coding=<encoding name>

or (using formats recognized by popular editors)或(使用流行编辑器认可的格式)

 #!/usr/bin/python # -*- coding: <encoding name> -*-

or要么

 #!/usr/bin/python # vim: set fileencoding=<encoding name> :

... ...

What I use in some project is this line in the first line for Linux machines:我在一些项目中使用的是 Linux 机器第一行中的这一行:

# -*- coding: utf-8 -*-

As a DOC & Author credit, I like simple string in multiline.作为 DOC 和作者的功劳,我喜欢多行中的简单字符串。 Here an example from Example Google Style Python Docstrings这里有一个来自Example Google Style Python Docstrings 的例子

# -*- coding: utf-8 -*-
"""Example Google style docstrings.

This module demonstrates documentation as specified by the `Google Python
Style Guide`_. Docstrings may extend over multiple lines. Sections are created
with a section header and a colon followed by a block of indented text.

Example:
    Examples can be given using either the ``Example`` or ``Examples``
    sections. Sections support any reStructuredText formatting, including
    literal blocks::

        $ python example_google.py

Section breaks are created by resuming unindented text. Section breaks
are also implicitly created anytime a new section starts.

Attributes:
    module_level_variable1 (int): Module level variables may be documented in
        either the ``Attributes`` section of the module docstring, or in an
        inline docstring immediately following the variable.

        Either form is acceptable, but the two should not be mixed. Choose
        one convention to document module level variables and be consistent
        with it.

Todo:
    * For module TODOs
    * You have to also use ``sphinx.ext.todo`` extension

.. _Google Python Style Guide:
   http://google.github.io/styleguide/pyguide.html

"""

Also can be nice to add:也可以很好地添加:

        """
        @Author: ...
        @Date: ....
        @Credit: ...
        @Links: ...
        """

Additional Formats附加格式

  • Meta-information markup | 元信息标记| devguide 开发者指南

    """ """

     :mod:`parrot` -- Dead parrot access =================================== .. module:: parrot :platform: Unix, Windows :synopsis: Analyze and reanimate dead parrots. .. moduleauthor:: Eric Cleese <eric@python.invalid> .. moduleauthor:: John Idle <john@python.invalid> """
  • /common-header-python /common-header-python

     #!/usr/bin/env python3 Line 1 # -*- coding: utf-8 -*- Line 2 #---------------------------------------------------------------------------- # Created By : name_of_the_creator Line 3 # Created Date: date/month/time ..etc # version ='1.0' # ---------------------------------------------------------------------------

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM