标签归档:comments

Python注释中的“#noqa”是什么意思?

问题:Python注释中的“#noqa”是什么意思?

在搜索Python项目时,我发现有几行用注释# noqa

import sys
sys.path.append(r'C:\dev')
import some_module   # noqa

noqa在Python 中是什么意思?它仅适用于Python吗?

While searching through a Python project, I found a few lines commented with # noqa.

import sys
sys.path.append(r'C:\dev')
import some_module   # noqa

What does noqa mean in Python? Is it specific to Python only?


回答 0

添加# noqa到一行表示该linter(自动检查代码质量的程序)不应检查该行。代码可能已生成的任何警告都将被忽略。

该行可能对短毛绒“看起来不好”,但由于某种原因,开发人员理解并打算将其放在那里。

有关更多信息,请参见Flake8文档,以选择和忽略违规

Adding # noqa to a line indicates that the linter (a program that automatically checks code quality) should not check this line. Any warnings that code may have generated will be ignored.

That line may have something that “looks bad” to the linter, but the developer understands and intends it to be there for some reason.

For more information, see the Flake8 documentation for Selecting and Ignoring Violations.


回答 1

noqa = NO-QA(无质量保证)

在Python编程中通常引用它来忽略PEP8警告。

简而言之,linter程序将忽略末尾带有#noqa的行,并且不会发出任何警告。

noqa = NO-QA (NO Quality Assurance)

It’s generally referred in Python Programming to ignore the PEP8 warnings.

In simple words, lines having #noqa at the end will be ignored by the linter programs and they won’t raise any warnings.


回答 2

你知道吗?甚至Guido van Rossum(Python的创建者):D 之前也问过这个问题。

有点词源# noqa

它曾经是“ nopep8”,但是当Flake8和Pep8想要一个普通的限定词时,@ florentx像“ No Quality Assurance”(iirc)中一样建议“ NoQA”,并且卡住了。

一些基本用法# noqa(与flake8):

  • # flake8: noqa:跳过包含此行的文件
  • 最后包含# noqa评论的:将不会发出警告
  • # noqa: <error>,例如# noqa: E234 最后:忽略一行中的 特定错误
    • 可以给出多个错误代码,以逗号分隔
    • 代码列表之前的冒号

You know what? Even Guido van Rossum (the creator of Python) asked this question before :D

A bit Etymology of # noqa:

It used to be “nopep8” but when Flake8 and Pep8 wanted a common qualifier @florentx suggested “NoQA” as in “No Quality Assurance” (iirc) and it stuck.

Some basic usages of # noqa (with flake8):

  • # flake8: noqa: files that contain this line are skipped
  • lines that contain a # noqa comment at the end: will not issue warnings
  • # noqa: <error>, e.g., # noqa: E234 at the end: ignore specific errors on a line
    • multiple error codes can be given, separated by comma
    • the colon before the list of codes is required

我可以在点子要求文件中添加注释吗?

问题:我可以在点子要求文件中添加注释吗?

我想在点子要求文件中添加一些包装的注释。(只是为了解释为什么该软件包在列表中。)我可以这样做吗?

我在想像

Babel==0.9.5 # translation
CherryPy==3.2.0 # web server
Creoleparser==0.7.1 # wiki formatting
Genshi==0.5.1 # templating

I’d like to add comments for a few packages in a pip requirements file. (Just to explain why that package is on the list.) Can I do this?

I’m imagining something like

Babel==0.9.5 # translation
CherryPy==3.2.0 # web server
Creoleparser==0.7.1 # wiki formatting
Genshi==0.5.1 # templating

回答 0

当然可以,只需使用 #

pipdocs

以#开头的行被视为注释并被忽略。空格后跟#会导致#和该行的其余部分被视为注释。

Sure, you can, just use #

pip docs:

A line that begins with # is treated as a comment and ignored. Whitespace followed by a # causes the # and the remainder of the line to be treated as a comment.


回答 1


为什么Python没有多行注释?

问题:为什么Python没有多行注释?

好的,我知道三引号字符串可以用作多行注释。例如,

"""Hello, I am a 
   multiline comment"""

'''Hello, I am a 
   multiline comment'''

但是从技术上讲,这些是字符串,对吗?

我已经在Google上搜索并阅读了Python样式指南,但是无法找到关于为什么没有正式实现多行,/ * * /注释类型的技术答案。我使用三重引号没有问题,但是我对导致这个设计决定的原因有点好奇。

OK, I’m aware that triple-quotes strings can serve as multiline comments. For example,

"""Hello, I am a 
   multiline comment"""

and

'''Hello, I am a 
   multiline comment'''

But technically speaking these are strings, correct?

I’ve googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.


回答 0

我怀疑您会得到比“ Guido不需要多行注释”更好的答案。

Guido在推特上发布了以下内容:

Python提示:您可以将多行字符串用作多行注释。除非用作文档字符串,否则它们不会生成任何代码!:-)

I doubt you’ll get a better answer than, “Guido didn’t feel the need for multi-line comments”.

Guido has tweeted about this:

Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)


回答 1

多行注释很容易被破坏。如果您在一个简单的计算器程序中拥有以下内容,该怎么办?

operation = ''
print("Pick an operation:  +-*/")
# Get user input here

尝试用多行注释对此进行注释:

/*
operation = ''
print("Pick an operation:  +-*/")
# Get user input here
*/

糟糕,您的字符串包含结尾注释定界符。

Multi-line comments are easily breakable. What if you have the following in a simple calculator program?

operation = ''
print("Pick an operation:  +-*/")
# Get user input here

Try to comment that with a multi-line comment:

/*
operation = ''
print("Pick an operation:  +-*/")
# Get user input here
*/

Oops, your string contains the end comment delimiter.


回答 2

用三引号括起来的文本不应视为多行注释;按照惯例,它们是docstrings。他们应该描述您的代码做什么以及如何使用它,而不是描述诸如注释代码块之类的内容。

根据Guido的说法,Python中的多行注释只是连续的单行注释(搜索“块注释”)。

为了注释代码块,我有时使用以下模式:

if False:
    # A bunch of code

Triple-quoted text should NOT be considered multi-line comments; by convention, they are docstrings. They should describe what your code does and how to use it, but not for things like commenting out blocks of code.

According to Guido, multiline comments in Python are just contiguous single-line comments (search for “block comments”).

To comment blocks of code, I sometimes use the following pattern:

if False:
    # A bunch of code

回答 3

这可能回到核心概念,即应该有一种显而易见的方法来完成一项任务。其他注释样式会增加不必要的复杂性,并可能降低可读性。

This likely goes back to the core concept that there should be one obvious way to do a task. Additional comment styles add unnecessary complications and could decrease readability.


回答 4

好吧,三引号用作文档字符串中的多行注释。#注释用作内联注释,人们逐渐习惯了。

大多数脚本语言也没有多行注释。也许是原因所在?

参见PEP 0008注释部分

并查看您的Python编辑器是否提供了一些用于块注释的键盘快捷键。Emacs以及Eclipse都支持它,大概大多数体面的IDE都支持。

Well, the triple-quotes are used as multiline comments in docstrings. And # comments are used as inline comments and people get use to it.

Most of script languages don’t have multiline comments either. Maybe that’s the cause?

See PEP 0008, section Comments

And see if your Python editor offers some keyboard shortcut for block commenting. Emacs supports it, as well as Eclipse, presumably most of decent IDEs does.


回答 5

Python的禅宗

应该有一种-最好只有一种-显而易见的方法。

From The Zen of Python:

There should be one– and preferably only one –obvious way to do it.


回答 6

就我个人而言,Java的评论风格就像

/*
 * My multi-line comment in Java
 */

因此,如果您的样式是前面示例的典型样式,那么仅具有单行注释并不是一件坏事,因为相比之下,您将拥有

#
# My multi-line comment in Python
#

VB.NET也是一种仅具有单行注释的语言,我个人认为它很烦人,因为注释最终看起来不像注释,而更像某种引用

'
' This is a VB.NET example
'

仅单行注释最终会比多行注释具有更少的字符使用率,并且在正则表达式语句中不太可能被某些狡猾的字符转义?不过,我倾向于同意内德。

Personally my comment style in say Java is like

/*
 * My multi-line comment in Java
 */

So having single-line only comments isn’t such a bad thing if your style is typical to the preceding example because in comparison you’d have

#
# My multi-line comment in Python
#

VB.NET is also a language with single-line only commenting, and personally I find it annoying as comments end up looking less likes comments and more like some kind of quote

'
' This is a VB.NET example
'

Single-line-only comments end up having less character-usage than multi-line comments, and are less likely to be escaped by some dodgy characters in a regex statement perhaps? I’d tend to agree with Ned though.


回答 7

Pycharm IDE中注释掉一段代码:

  • 代码 带线注释
  • Windows或Linux:Ctrl+/
  • Mac OS:Command+/

To comment out a block of code in the Pycharm IDE:

  • Code | Comment with Line Comment
  • Windows or Linux: Ctrl + /
  • Mac OS: Command + /

回答 8

# This
# is
# a 
# multi-line
# comment

使用注释块或在编辑器中搜索并替换(s / ^ /#/ g)即可实现此目的。

# This
# is
# a 
# multi-line
# comment

Use comment block or search and replace (s/^/#/g) in your editor to achieve this.


回答 9

我通过为文本编辑器(TextPad)下载宏解决了这一问题,该宏使我可以突出显示行,然后在每行的第一行插入#。类似的宏将删除#。有人可能会问为什么需要多行,但是当您尝试“关闭”代码块以进行调试时,它会派上用场。

I solved this by downloading a macro for my text editor (TextPad) that lets me highlight lines and it then inserts # at the first of each line. A similar macro removes the #’s. Some may ask why multiline is necessary but it comes in handy when you’re trying to “turn off” a block of code for debugging purposes.


回答 10

对于在Python中寻找多行注释的其他人-使用三引号格式可能会产生一些问题,因为我刚刚学到了很难的方法。考虑一下:

this_dict = {
    'name': 'Bob',

"""
This is a multiline comment in the middle of a dictionary
"""

    'species': 'Cat'
}

多行注释将被塞入下一个字符串中,从而弄乱了 'species'密钥。最好仅#用于评论。

For anyone else looking for multi-line comments in Python – using the triple quote format can have some problematic consequences, as I’ve just learned the hard way. Consider this:

this_dict = {
    'name': 'Bob',

"""
This is a multiline comment in the middle of a dictionary
"""

    'species': 'Cat'
}

The multi-line comment will be tucked into the next string, messing up the 'species' key. Better to just use # for comments.


回答 11

因为#约定是常见的约定,所以对于多行注释,您实际上无能为力,而对#符号注释则无能为力。这是历史性的意外,就像/* ... */回溯到PL / I 的评论之初一样,

Because the # convention is a common one, and there really isn’t anything you can do with a multiline comment that you can’t with a #-sign comment. It’s a historical accident, like the ancestry of /* ... */ comments going back to PL/I,


回答 12

假设只是认为它们是不必要的。由于键入非常容易,因此#a comment多行注释只能包含许多单行注释。

另一方面,对于HTML,更需要多行。很难继续打字<!--comments like this-->

Assume that they were just considered unnecessary. Since it’s so easy to just type #a comment, multiline comments can just consist of many single line comments.

For HTML, on the other hand, there’s more of a need for multiliners. It’s harder to keep typing <!--comments like this-->.


回答 13

这只是一个猜测..但是

因为它们是字符串,所以它们具有一些语义值(编译器不会摆脱它们),因此将它们用作文档字符串是有意义的。它们实际上成为AST的一部分,因此提取文档变得更加容易。

This is just a guess .. but

Because they are strings, they have some semantic value (the compiler doesn’t get rid of them), therefore it makes sense for them to be used as docstrings. They actually become part of the AST, so extracting documentation becomes easier.


回答 14

此外,多行注释是一个bit子。抱歉地说,但是不管使用哪种语言,我都不会将它们用于调试目的。假设您有这样的代码:

void someFunction()
{
    Something
    /*Some comments*/
    Something else
}

然后,您会发现代码中有些内容无法使用调试器进行修复,因此您可以通过使用多行注释注释掉越来越小的代码块来开始手动调试它。然后将提供以下功能:

void someFunction()
{ /*
    Something
   /* Comments */
   Something more*/
}

这真令人讨厌。

Besides, multiline comments are a bitch. Sorry to say, but regardless of the language, I don’t use them for anything else than debugging purposes. Say you have code like this:

void someFunction()
{
    Something
    /*Some comments*/
    Something else
}

Then you find out that there is something in your code you can’t fix with the debugger, so you start manually debugging it by commenting out smaller and smaller chuncks of code with theese multiline comments. This would then give the function:

void someFunction()
{ /*
    Something
   /* Comments */
   Something more*/
}

This is really irritating.


回答 15

使用IDLE的多行注释:

  • Mac OS X中,后选码,注释与代码块Ctrl+ 3并取消使用Ctrl+ 4

  • Windows,选择代码后,用Ctrl+ Alt+ 注释一段代码,3然后使用Ctrl+ At+ 取消注释4

Multiline comments using IDLE on:

  • Mac OS X, after code selection, comment a block of code with Ctrl+3 and uncomment using Ctrl+4.

  • Windows, after code selection, comment a block of code with Ctrl+Alt+3 and uncomment using Ctrl+At+4.


回答 16

我记得读过一篇关于将多行注释放入三引号中的变量的家伙的文章:

x = '''
This is my
super-long mega-comment.
Wow there are a lot of lines
going on here!
'''

这确实占用了一些内存,但是它为您提供了多行注释功能,并且大多数编辑器都会为您突出显示语法:)

通过简单地将其包装起来,注释掉代码也很容易

x = '''

'''

I remember reading about one guy who would put his multi-line comments into a triple-quoted variable:

x = '''
This is my
super-long mega-comment.
Wow there are a lot of lines
going on here!
'''

This does take up a bit of memory, but it gives you multi-line comment functionality, and plus most editors will highlight the syntax for you :)

It’s also easy to comment out code by simply wrapping it with

x = '''

and

'''

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

问题:Python文件的常见标头格式是什么?

在有关Python编码准则的文档中,我遇到了以下Python源文件的头格式:

#!/usr/bin/env python

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

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

这是Python世界中标头的标准格式吗?我还可以在标题中添加哪些其他字段/信息?Python专家分享了有关好的Python源标头的指南:-)

I came across the following header format for Python source files in a document about Python coding guidelines:

#!/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? What other fields/information can I put in the header? Python gurus share your guidelines for good Python source headers :-)


回答 0

它是Foobar模块的所有元数据。

第一个是docstring模块的,已经在Peter的答案中进行了解释。

如何组织模块(源文件)?(存档)

每个文件的第一行应为#!/usr/bin/env python这样就可以将文件作为脚本运行,例如在CGI上下文中隐式调用解释器。

接下来应该是带有说明的文档字符串。如果描述很长,那么第一行应该是一个简短的摘要,该摘要应具有其自身的意义,并以换行符分隔其余部分。

所有代码(包括import语句)都应遵循docstring。否则,解释器将无法识别该文档字符串,并且您将无法在交互式会话中访问该文档字符串(例如,通过obj.__doc__)或使用自动化工具生成文档时。

首先导入内置模块,然后导入第三方模块,然后再导入路径和您自己的模块。特别是,模块的路径和名称的添加可能会快速更改:将它们放在一个位置可以使它们更容易找到。

接下来应该是作者信息。此信息应遵循以下格式:

__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"

状态通常应为“原型”,“开发”或“生产”之一。__maintainer__应该是将修复错误并进行改进(如果导入)的人。__credits__不同之处在于__author__,这些__credits__人报告了错误修复,提出了建议等,但实际上并未编写代码。

在这里你有更多的信息,上市__author____authors____contact____copyright____license____deprecated____date____version__作为公认的元数据。

Its all metadata for the Foobar module.

The first one is the docstring of the module, that is already explained in Peter’s answer.

How do I organize my modules (source files)? (Archive)

The first line of each file shoud be #!/usr/bin/env python. This makes it possible to run the file as a script invoking the interpreter implicitly, e.g. in a CGI context.

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 (i.e. through obj.__doc__) or when generating documentation with automated tools.

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. __credits__ differs from __author__ in that __credits__ includes people who reported bug fixes, made suggestions, etc. but did not actually write the code.

Here you have more information, listing __author__, __authors__, __contact__, __copyright__, __license__, __deprecated__, __date__ and __version__ as recognized metadata.


回答 1

我强烈赞成使用最少的文件头,我的意思是:

  • #!如果是可执行脚本,则使用hashbang(行)
  • 模块文档字符串
  • 导入,以标准方式分组,例如:
  import os    # standard library
  import sys

  import requests  # 3rd party packages

  import mypackage.mymodule  # local source
  import mypackage.myothermodule  

即。三组进口,它们之间有一个空白行。在每个组中,对进口进行排序。最后一组,从本地来源进口,可以是如图所示的绝对进口,也可以是明确的相对进口。

其他所有内容都浪费时间,占用视觉空间,并且会产生误导。

如果您有法律免责声明或许可信息,它将进入一个单独的文件中。它不需要感染每个源代码文件。您的版权应该是其中的一部分。人们应该可以在您的网站上找到它LICENSE文件中,而不是随机的源代码。

源代码控件已经维护了诸如作者身份和日期之类的元数据。无需在文件本身中添加更详细,错误且过时的相同信息版本。

我不认为每个人都需要将任何其他数据放入其所有源文件中。您可能有这样做的特定要求,但是根据定义,这种情况仅适用于您。它们在“为所有人推荐的通用标题”中没有位置。

I strongly favour minimal file headers, by which I mean just:

  • The hashbang (#! line) if this is an executable script
  • Module docstring
  • Imports, grouped in the standard way, eg:
  import os    # standard library
  import sys

  import requests  # 3rd party packages

  import mypackage.mymodule  # local source
  import mypackage.myothermodule  

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.

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”.


回答 2

上面的答案确实很完整,但是如果您想要一个快速且脏的标题来复制粘贴,请使用以下命令:

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

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

为什么这是一个好人:

  • 第一行适用于* nix用户。它将在用户路径中选择Python解释器,因此将自动选择用户首选的解释器。
  • 第二个是文件编码。如今,每个文件都必须具有关联的编码。UTF-8可以在任何地方使用。只是遗留项目会使用其他编码。
  • 和一个非常简单的文档。它可以填充多行。

也可以看看: https //www.python.org/dev/peps/pep-0263/

如果仅在每个文件中编写一个类,则甚至不需要文档(它会放在类doc中)。

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. It will choose the Python interpreter in the user path, so will automatically choose the user preferred interpreter.
  • The second one is the file encoding. Nowadays every file must have a encoding associated. UTF-8 will work everywhere. 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/

If you just write a class in each file, you don’t even need the documentation (it would go inside the class doc).


回答 3

如果使用的是非ASCII字符集,另请参阅PEP 263

抽象

该PEP建议引入一种语法,以声明Python源文件的编码。然后,Python解析器将使用编码信息使用给定的编码来解释文件。最值得注意的是,这增强了源代码中Unicode文字的解释,并使得可以在例如Unicode的编辑器中直接使用UTF-8编写Unicode文字。

问题

在Python 2.1中,只能使用基于Latin-1的编码“ unicode-escape”编写Unicode文字。这使得编程环境对在许多亚洲国家这样的非拉丁1语言环境中生活和工作的Python用户而言相当不利。程序员可以使用最喜欢的编码来编写其8位字符串,但是绑定到Unicode文字的“ unicode-escape”编码。

拟议的解决方案

我建议通过在文件顶部使用特殊注释来声明编码,从而使每个源文件都可以看到和更改Python源代码。

为了使Python知道此编码声明,在处理Python源代码数据方面需要进行一些概念上的更改。

定义编码

如果未提供其他编码提示,Python将默认使用ASCII作为标准编码。

要定义源代码编码,必须将魔术注释作为源文件的第一行或第二行放置在源文件中,例如:

      # coding=<encoding name>

或(使用流行的编辑器认可的格式)

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

要么

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

Also see PEP 263 if you are using a non-ascii characterset

Abstract

This PEP proposes to introduce a syntax to declare the encoding of a Python source file. The encoding information is then used by the Python parser to interpret the file using the given encoding. Most notably this enhances the interpretation of Unicode literals in the source code and makes it possible to write Unicode literals using e.g. UTF-8 directly in an Unicode aware editor.

Problem

In Python 2.1, Unicode literals can only be written using the Latin-1 based encoding “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. Programmers can write their 8-bit strings using the favorite encoding, but are bound to the “unicode-escape” encoding for Unicode literals.

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.

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.

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given.

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> :


有没有办法在Python中创建多行注释?

问题:有没有办法在Python中创建多行注释?

我最近开始研究Python,但是找不到如何实现多行注释。大多数语言都有块注释符号,例如

/*

*/

我在Python中尝试过此方法,但它引发了错误,因此这可能不是正确的方法。Python实际上是否具有多行注释功能?

I have recently started studying Python, but I couldn’t find how to implement multi-line comments. Most languages have block comment symbols like

/*

*/

I tried this in Python, but it throws an error, so this probably is not the correct way. Does Python actually have a multiline comment feature?


回答 0

您可以使用三引号引起来的字符串。如果它们不是文档字符串(类/函数/模块中的第一件事),则将其忽略。

'''
This is a multiline
comment.
'''

(请确保'''适当缩进引线,以避免出现IndentationError。)

Guido van Rossum(Python的创建者)在推特上发了一条“专业提示”。

但是,Python的样式指南PEP8 倾向于使用连续的单行注释,这也是在许多项目中都可以找到的。文本编辑器通常具有快捷方式来轻松实现此目的。

You can use triple-quoted strings. When they’re not a docstring (the first thing in a class/function/module), they are ignored.

'''
This is a multiline
comment.
'''

(Make sure to indent the leading ''' appropriately to avoid an IndentationError.)

Guido van Rossum (creator of Python) tweeted this as a “pro tip”.

However, Python’s style guide, PEP8, favors using consecutive single-line comments, and this is also what you’ll find in many projects. Text editors usually have a shortcut to do this easily.


回答 1

从某种意义上说,Python确实具有多行字符串/注释语法,除非多行字符串不用作文档字符串,否则不会生成字节码 -就像- #前置注释一样。实际上,它的行为就像评论一样。

另一方面,如果您说必须在官方文档中记录此行为才是真正的注释语法,那么可以,您可以肯定地说这不是语言规范的一部分。

无论如何,您的文本编辑器还应该能够轻松注释掉所选区域(通过#在每个行的前面分别放置一个)。如果不是,请切换到可以的文本编辑器。

没有某些文本编辑功能的Python编程可能会很痛苦。找到合适的编辑器(并知道如何使用它)可以在如何理解Python编程经验方面产生很大的不同。

文本编辑器不仅能够注释掉选定的区域,还应该能够轻松地向左和向右移动代码块,并且当您按时它应该自动将光标置于当前的缩进级别Enter。代码折叠也很有用。


为了防止链路衰减,这是Guido van Rossum的推文的内容

@BSUCSClub Python提示:您可以将多行字符串用作多行注释。除非用作文档字符串,否则它们不会生成任何代码!:-)

Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode — just like #-prepended comments. In effect, it acts exactly like a comment.

On the other hand, if you say this behavior must be documented in the official documentation to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.

In any case, your text editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to a text editor that does.

Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.

Not only should the text editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and it should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.


To protect against link decay, here is the content of Guido van Rossum’s tweet:

@BSUCSClub Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)


回答 2

从接受的答案…

您可以使用三引号引起来的字符串。如果它们不是文档字符串(类/函数/模块中的第一件事),则将其忽略。

这是不正确的。与注释不同,三引号字符串仍然会被解析,并且在语法上必须有效,无论它们在源代码中的位置如何。

如果您尝试运行此代码…

def parse_token(token):
    """
    This function parses a token.
    TODO: write a decent docstring :-)
    """

    if token == '\\and':
        do_something()

    elif token == '\\or':
        do_something_else()

    elif token == '\\xor':
        '''
        Note that we still need to provide support for the deprecated
        token \xor. Hopefully we can drop support in libfoo 2.0.
        '''
        do_a_different_thing()

    else:
        raise ValueError

你会得到…

ValueError: invalid \x escape

…在Python 2.x上…

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 79-80: truncated \xXX escape

…在Python 3.x上。

进行解析器忽略的多行注释的唯一方法是…

elif token == '\\xor':
    # Note that we still need to provide support for the deprecated
    # token \xor. Hopefully we can drop support in libfoo 2.0.
    do_a_different_thing()

From the accepted answer…

You can use triple-quoted strings. When they’re not a docstring (first thing in a class/function/module), they are ignored.

This is simply not true. Unlike comments, triple-quoted strings are still parsed and must be syntactically valid, regardless of where they appear in the source code.

If you try to run this code…

def parse_token(token):
    """
    This function parses a token.
    TODO: write a decent docstring :-)
    """

    if token == '\\and':
        do_something()

    elif token == '\\or':
        do_something_else()

    elif token == '\\xor':
        '''
        Note that we still need to provide support for the deprecated
        token \xor. Hopefully we can drop support in libfoo 2.0.
        '''
        do_a_different_thing()

    else:
        raise ValueError

You’ll get either…

ValueError: invalid \x escape

…on Python 2.x or…

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 79-80: truncated \xXX escape

…on Python 3.x.

The only way to do multi-line comments which are ignored by the parser is…

elif token == '\\xor':
    # Note that we still need to provide support for the deprecated
    # token \xor. Hopefully we can drop support in libfoo 2.0.
    do_a_different_thing()

回答 3

在Python 2.7中,多行注释为:

"""
This is a
multilline comment
"""

如果您在Class里,应该正确地选择它。

例如:

class weather2():
   """
   def getStatus_code(self, url):
       world.url = url
       result = requests.get(url)
       return result.status_code
   """

In Python 2.7 the multiline comment is:

"""
This is a
multilline comment
"""

In case you are inside a class you should tab it properly.

For example:

class weather2():
   """
   def getStatus_code(self, url):
       world.url = url
       result = requests.get(url)
       return result.status_code
   """

回答 4

AFAIK,Python没有阻止注释。要注释单个行,可以使用该#字符。

如果使用的是Notepad ++则有一个用于块注释的快捷方式。我敢肯定,像gVimEmacs这样的人也有类似的功能。

AFAIK, Python doesn’t have block comments. For commenting individual lines, you can use the # character.

If you are using Notepad++, there is a shortcut for block commenting. I’m sure others like gVim and Emacs have similar features.


回答 5

我认为没有,除了未处理多行字符串。但是,大多数(如果不是全部)Python IDE都具有用于“注释”多行代码的快捷键。

I think it doesn’t, except that a multiline string isn’t processed. However, most, if not all Python IDEs have a shortkey for ‘commenting out’ multiple lines of code.


回答 6

如果您发表评论

"""
long comment here
"""

在脚本中间,Python / lint无法识别。折叠将被弄乱,因为以上注释不是标准建议的一部分。最好用

# Long comment
# here.

如果使用Vim,则可以使用commentary.vim之类的插件通过按来自动注释掉较长的注释行Vjgcc。在其中Vj选择两行代码,并将gcc其注释掉。

如果您不想使用上述插件,则可以使用搜索和替换类似

:.,.+1s/^/# /g

这会将当前和下一行的第一个字符替换为#

If you put a comment in

"""
long comment here
"""

in the middle of a script, Python/linters won’t recognize that. Folding will be messed up, as the above comment is not part of the standard recommendations. It’s better to use

# Long comment
# here.

If you use Vim, you can plugins like commentary.vim, to automatically comment out long lines of comments by pressing Vjgcc. Where Vj selects two lines of code, and gcc comments them out.

If you don’t want to use plugins like the above you can use search and replace like

:.,.+1s/^/# /g

This will replace the first character on the current and next line with #.


回答 7

没有多行注释等功能。#是注释一行代码的唯一方法。你们中的许多人都回答”’评论”’作为他们的解决方案。

它似乎可行,但是'''在Python 内部,它使用常规字符串将封闭的行作为解释器不会忽略的注释之类的注释#

在此处查看官方文档

There is no such feature as a multi-line comment. # is the only way to comment a single line of code. Many of you answered ”’ a comment ”’ this as their solution.

It seems to work, but internally ''' in Python takes the lines enclosed as a regular strings which the interpreter does not ignores like comment using #.

Check the official documentation here


回答 8

不幸的是,字符串化不能总是用作注释!因此,更安全的做法是坚持在每行前面加一个#

这是一个例子:

test1 = [1, 2, 3, 4,]       # test1 contains 4 integers

test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'

Unfortunately stringification can not always be used as commenting out! So it is safer to stick to the standard prepending each line with a #.

Here is an example:

test1 = [1, 2, 3, 4,]       # test1 contains 4 integers

test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'

回答 9

好了,您可以尝试一下(在运行引号时,第一个问题的输入应用引号'):

"""
print("What's your name? ")
myName = input()
print("It's nice to meet you " + myName)
print("Number of characters is ")
print(len(myName))
age = input("What's your age? ")
print("You will be " + str(int(age)+1) + " next year.")

"""
a = input()
print(a)
print(a*5)

包括在内的任何内容"""都会被评论。

如果您要查找单行注释,则为#

Well, you can try this (when running the quoted, the input to the first question should quoted with '):

"""
print("What's your name? ")
myName = input()
print("It's nice to meet you " + myName)
print("Number of characters is ")
print(len(myName))
age = input("What's your age? ")
print("You will be " + str(int(age)+1) + " next year.")

"""
a = input()
print(a)
print(a*5)

Whatever enclosed between """ will be commented.

If you are looking for single-line comments then it’s #.


回答 10

Python中的多行注释:

对我来说,“”和“”都有效。

例:

a = 10
b = 20
c = a+b
'''
print ('hello')
'''
print ('Addition is: ', a+b)

例:

a = 10
b = 20
c = a+b
"""
print('hello')
"""
print('Addition is: ', a+b)

Multiline comment in Python:

For me, both ”’ and “”” worked.

Example:

a = 10
b = 20
c = a+b
'''
print ('hello')
'''
print ('Addition is: ', a+b)

Example:

a = 10
b = 20
c = a+b
"""
print('hello')
"""
print('Addition is: ', a+b)

回答 11

Python中的内联注释以井号字符开头。

hello = "Hello!" # This is an inline comment
print(hello)

你好!

请注意,字符串文字中的哈希字符只是哈希字符。

dial = "Dial #100 to make an emergency call."
print(dial)

拨打#100拨打紧急电话。

哈希字符也可以用于单行或多行注释。

hello = "Hello"
world = "World"
# First print hello
# And print world
print(hello)
print(world)

你好

世界

用三重双引号将文本括起来以支持文档字符串。

def say_hello(name):
    """
    This is docstring comment and
    it's support multi line.
    :param name it's your name
    :type name str
    """
    return "Hello " + name + '!'


print(say_hello("John"))

你好约翰!

将文本用三重单引号引起来以用于块注释。

'''
I don't care the parameters and
docstrings here.
'''

The inline comments in Python starts with a hash character.

hello = "Hello!" # This is an inline comment
print(hello)

Hello!

Note that a hash character within a string literal is just a hash character.

dial = "Dial #100 to make an emergency call."
print(dial)

Dial #100 to make an emergency call.

A hash character can also be used for single or multiple lines comments.

hello = "Hello"
world = "World"
# First print hello
# And print world
print(hello)
print(world)

Hello

World

Enclose the text with triple double quotes to support docstring.

def say_hello(name):
    """
    This is docstring comment and
    it's support multi line.
    :param name it's your name
    :type name str
    """
    return "Hello " + name + '!'


print(say_hello("John"))

Hello John!

Enclose the text with triple single quotes for block comments.

'''
I don't care the parameters and
docstrings here.
'''

回答 12

在Python 2.7.13上:

单:

"A sample single line comment "

多行:

"""
A sample
multiline comment
on PyCharm
"""

On Python 2.7.13:

Single:

"A sample single line comment "

Multiline:

"""
A sample
multiline comment
on PyCharm
"""

回答 13

Visual Studio Code通用官方多行注释切换。

macOS:选择代码块,然后+/

Windows:选择代码块,然后Ctrl+/

Visual Studio Code universal official multi-line comment toggle.

macOS: Select code-block and then +/

Windows: Select code-block and then Ctrl+/


回答 14

是的,可以同时使用以下两种:

'''
Comments
'''

"""
Comments
"""

但是,在IDE中运行时,您唯一需要记住的是,您必须“运行”整个文件才能被多行代码接受。逐行“运行”将无法正常工作,并会显示错误。

Yes, it is fine to use both:

'''
Comments
'''

and

"""
Comments
"""

But, the only thing you all need to remember while running in an IDE, is you have to ‘RUN’ the entire file to be accepted as multiple lines codes. Line by line ‘RUN’ won’t work properly and will show an error.


回答 15

要注释掉Python中的多行代码,只需#在每一行上使用单行注释:

# This is comment 1
# This is comment 2 
# This is comment 3

要在Python中编写“适当的”多行注释,是使用具有"""语法的多行字符串Python具有文档字符串(或文档字符串)功能。它为程序员提供了一种在每个Python模块,函数,类和方法中添加快速注释的简便方法。

'''
This is
multiline
comment
'''

另外,请注意,您可以通过这样的类对象访问docstring

myobj.__doc__

For commenting out multiple lines of code in Python is to simply use a # single-line comment on every line:

# This is comment 1
# This is comment 2 
# This is comment 3

For writing “proper” multi-line comments in Python is to use multi-line strings with the """ syntax Python has the documentation strings (or docstrings) feature. It gives programmers an easy way of adding quick notes with every Python module, function, class, and method.

'''
This is
multiline
comment
'''

Also, mention that you can access docstring by a class object like this

myobj.__doc__

回答 16

您可以使用以下内容。这称为DockString。

def my_function(arg1):
    """
    Summary line.
    Extended description of function.
    Parameters:
    arg1 (int): Description of arg1
    Returns:
    int: Description of return value
    """
    return arg1

print my_function.__doc__

You can use the following. This is called DockString.

def my_function(arg1):
    """
    Summary line.
    Extended description of function.
    Parameters:
    arg1 (int): Description of arg1
    Returns:
    int: Description of return value
    """
    return arg1

print my_function.__doc__

回答 17

我建议不要使用"""多行注释!

这是一个简单的示例,以突出显示可能被视为意外行为的内容:

print('{}\n{}'.format(
    'I am a string',
    """
    Some people consider me a
    multi-line comment, but
    """
    'clearly I am also a string'
    )
)

现在看一下输出:

I am a string

    Some people consider me a
    multi-line comment, but
    clearly I am also a string

多行字符串不被视为注释,而是与之连接'clearly I'm also a string'形成一个字符串。

如果要注释多行,请按照PEP 8准则进行注释

print('{}\n{}'.format(
    'I am a string',
    # Some people consider me a
    # multi-line comment, but
    'clearly I am also a string'
    )
)

输出:

I am a string
clearly I am also a string

I would advise against using """ for multi line comments!

Here is a simple example to highlight what might be considered an unexpected behavior:

print('{}\n{}'.format(
    'I am a string',
    """
    Some people consider me a
    multi-line comment, but
    """
    'clearly I am also a string'
    )
)

Now have a look at the output:

I am a string

    Some people consider me a
    multi-line comment, but
    clearly I am also a string

The multi line string was not treated as comment, but it was concatenated with 'clearly I'm also a string' to form a single string.

If you want to comment multiple lines do so according to PEP 8 guidelines:

print('{}\n{}'.format(
    'I am a string',
    # Some people consider me a
    # multi-line comment, but
    'clearly I am also a string'
    )
)

Output:

I am a string
clearly I am also a string

回答 18

使用PyCharm IDE。

您可以使用Ctrl + /commentuncomment代码行。Ctrl + /注释或取消注释当前行或用单行注释注释掉若干行({# in Django templates, or # in Python scripts)Pressing Ctrl+Shift+/对于Django模板中选定的源代码块,该块用{% comment %} and {% endcomment %}标签包围。


n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)

print("Loop ended.")

选择所有行,然后按 Ctrl + /


# n = 5
# while n > 0:
#     n -= 1
#     if n == 2:
#         break
#     print(n)

# print("Loop ended.")

Using PyCharm IDE.

You can comment and uncomment lines of code using Ctrl+/. Ctrl+/ comments or uncomments the current line or several selected lines with single line comments ({# in Django templates, or # in Python scripts). Pressing Ctrl+Shift+/ for a selected block of source code in a Django template surrounds the block with {% comment %} and {% endcomment %} tags.


n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)

print("Loop ended.")

Select all lines then press Ctrl + /


# n = 5
# while n > 0:
#     n -= 1
#     if n == 2:
#         break
#     print(n)

# print("Loop ended.")

回答 19

多行注释实际上在Python中不存在。下面的示例包含一个未分配的字符串,该字符串已通过Python验证是否存在语法错误。

一些文本编辑器,例如Notepad ++,为我们提供了注释掉一段书面代码或单词的快捷方式。

def foo():
    "This is a doc string."
    # A single line comment
    """
       This
       is a multiline
       comment/String
    """
    """
    print "This is a sample foo function"
    print "This function has no arguments"
    """
    return True

另外,Ctrl+ K是Notepad ++中阻止评论的快捷方式。它#在所选内容的每行前面添加一个。Ctrl+ Shift+ K用于取消注释。

A multiline comment doesn’t actually exist in Python. The below example consists of an unassigned string, which is validated by Python for syntactical errors.

A few text editors, like Notepad++, provide us shortcuts to comment out a written piece of code or words.

def foo():
    "This is a doc string."
    # A single line comment
    """
       This
       is a multiline
       comment/String
    """
    """
    print "This is a sample foo function"
    print "This function has no arguments"
    """
    return True

Also, Ctrl + K is a shortcut in Notepad++ to block comment. It adds a # in front of every line under the selection. Ctrl + Shift + K is for block uncomment.


回答 20

在其他答案中,我发现最简单的方法是使用IDE注释函数,该函数使用的Python注释支持#

我正在使用Anaconda Spyder,它具有:

  • Ctrl+ 1-评论/取消评论
  • Ctrl+ 4-注释一段代码
  • Ctrl+ 5-取消注释代码块

它将使用注释/取消注释单行/多行代码#

我觉得最简单。

例如,一个块注释:

# =============================================================================
#     Sample Commented code in spyder
#  Hello, World!
# =============================================================================

Among other answers, I find the easiest way is to use the IDE comment functions which use the Python comment support of #.

I am using Anaconda Spyder and it has:

  • Ctrl + 1 – Comment/uncomment
  • Ctrl + 4 – Comment a block of code
  • Ctrl + 5 – Uncomment a block of code

It would comment/uncomment a single/multi line/s of code with #.

I find it the easiest.

For example, a block comment:

# =============================================================================
#     Sample Commented code in spyder
#  Hello, World!
# =============================================================================

回答 21

选择要注释的行,然后使用Ctrl+ ?注释或取消注释Sublime Text中的Python代码。编辑器中。

对于单行,可以使用Shift+ #

Select the lines that you want to comment and then use Ctrl + ? to comment or uncomment the Python code in the Sublime Text editor.

For single line you can use Shift + #.