Python 中 help() 函数的各种特性
Python 有一个用于获取帮助的内置help
函数……但help
能做什么呢?
help
函数可以用来查找以下文档:
- 函数
- 模块
- 任何对象
- 符号
- 关键词
- Topics
让我们来看看help
的所有 6 种用法。我们将从最常见的 3 种用途开始:函数、模块和所有其他对象。
向 help 传递对象
在使用 help 函数时,我几乎总是传递一个对象给它:函数、模块、类或类实例。
向 help(…) 传递一个函数对象 (是的,函数在 Python 中是对象) 将显示该函数的 docstring:
>>>help(print)
Help on built-in function print in module builtins:
print(*args, sep=' ', end='\n', file=None, flush=False)
Prints the values to a stream, or to sys.stdout by default.
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
传递一个类或类的实例将显示该类的文档字符串以及类中每个方法的文档:
>>>numbers = [2, 1, 3, 4]
>>> help(numbers)
Help on list object:
class list(object)
| list(iterable=(), /)
|
| Built-in mutable sequence.
|
| If no argument is given, the constructor creates a new empty list.
| The argument must be an iterable if specified.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
... [Many more methods shown after this]
传递模块对象将显示模块内所有内容的文档:
>>>import math
>>> help(math)
Help on module math:
NAME
math
MODULE REFERENCE
https://docs.python.org/3.13/library/math.html
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
DESCRIPTION
This module provides access to the mathematical functions
defined by the C standard.
FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.
The result is between 0 and pi.
acosh(x, /)
Return the inverse hyperbolic cosine of x.
... [Many more functions shown after this, as well as data attributes]
您还可以将方法对象(方法只是附加到类上的函数)或模块中的函数传递到help
中:
>>>help(numbers.pop)
Help on built-in function pop:
pop(index=-1, /) method of builtins.list instance
Remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
>>> help(math.sqrt)
Help on built-in function sqrt in module math:
sqrt(x, /)
Return the square root of x.
使用help
功能还有其他方法,但在深入探讨之前,我想先谈谈上面输出中显示的 * 和 / 符号。
题外话:键盘快捷键
进入help
后,如何四处走动?此外,如何help
帮助?
在不同的平台上,help
函数支持不同的快捷键,这有点遗憾。
在 Windows 上,Python help
功能通常使用 more 命令。在 Linux 和 Mac 上,它使用 less 命令。
在 Linux 和 Mac 上,最有用的help
快捷键是
Down
或j
一次向下滚动一行Up
或k
一次向上滚动一行Ctrl-D
向下滚动半个屏幕Ctrl-U
向上滚动半个屏幕/
在当前帮助页面内向下搜索?
在当前帮助页面内向上搜索q
退出help
在 Windows 上,help
最有用的快捷键是
Enter
每次向下浏览一行Space
向下浏览半个屏幕q
退出
Python 使用的more
或 less
程序(取决于操作系统)被称为 “寻呼机”。如果您安装了更高级的寻呼机程序,您可以设置 PAGER
或 MANPAGER
环境变量,自定义使用哪个寻呼机程序。
获取关于字符串的帮助
help
函数接受任何对象,并返回关于该对象的帮助。但 help
函数也接受字符串:
>>>help("math.prod")
Help on built-in function prod in math:
math.prod = prod(iterable, /, *, start=1)
Calculate the product of all the elements in the input iterable.
The default start value for the product is 1.
When the iterable is empty, return the start value. This function is
intended specifically for use with numeric values and may reject
non-numeric types.
这对于获取尚未导入到 Python REPL 的实用程序的帮助非常方便。
但这也意味着,我们不能向 help 传递一个字符串,并期望得到关于 str
类型的帮助:
>>> name = "Trey"
>>> help(name)
No Python documentation found for 'Trey'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.
要获得有关字符串的帮助,需要输入字符串类,而不是字符串实例:
>>> help(str)
Help on class str in module builtins:
class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to 'utf-8'.
| errors defaults to 'strict'.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
... [Many more methods shown after this]
查找 symbols, keywords, 和 topics
传递给 help 的字符串并不一定要代表 Python 对象的路径。help
函数也接受表示symbols 、关键字和主题的字符串。
查找有关symbols 的帮助
在 Python 中,symbols 不是对象,因此不能作为参数传递给help
:
>>> help(**)
File "<unknown>", line 1
help(**)
^
SyntaxError: invalid syntax
要查询某个符号的帮助信息,可以向help
函数传递一个字符串。例如,在这里我们要查找 ** 运算符的作用:
>>> help("**")
The power operator
******************
The power operator binds more tightly than unary operators on its
left; it binds less tightly than unary operators on its right. The
syntax is:
power ::= (await_expr | primary) ["**" u_expr]
Thus, in an unparenthesized sequence of power and unary operators, the
operators are evaluated from right to left (this does not constrain
the evaluation order for the operands): "-1**2" results in "-1".
The power operator has the same semantics as the built-in "pow()"
function, when called with two arguments: it yields its left argument
raised to the power of its right argument. The numeric arguments are
first converted to a common type, and the result is of that type.
For int operands, the result has the same type as the operands unless
the second argument is negative; in that case, all arguments are
converted to float and a float result is delivered. For example,
"10**2" returns "100", but "10**-2" returns "0.01".
Raising "0.0" to a negative power results in a "ZeroDivisionError".
Raising a negative number to a fractional power results in a "complex"
number. (In earlier versions it raised a "ValueError".)
This operation can be customized using the special "__pow__()" and
"__rpow__()" methods.
Related help topics: EXPRESSIONS, OPERATORS
查找有关 Keywords 的帮助
关键字是不能用作有效 Python 变量名的词。
例如,class
、if
、for
和 return
是 Python 语法中使用的关键字。试图将这些关键字传递给 help
会导致语法错误:
>>> help(return)
File "<python-input-0>", line 1
help(return)
^^^^^^
SyntaxError: invalid syntax
与符号一样,您可以将关键字以字符串的形式传递给help
函数,从而获得关键字的帮助:
>>> help("if")
The "if" statement
******************
The "if" statement is used for conditional execution:
if_stmt ::= "if" assignment_expression ":" suite
("elif" assignment_expression ":" suite)*
["else" ":" suite]
It selects exactly one of the suites by evaluating the expressions one
by one until one is found to be true (see section Boolean operations
for the definition of true and false); then that suite is executed
(and no other part of the "if" statement is executed or evaluated).
If all expressions are false, the suite of the "else" clause, if
present, is executed.
Related help topics: TRUTHVALUE
查找有关 topics 的帮助
您可能已经注意到某些帮助文档底部列出了 “相关帮助 topics”。要获得其中一个topics的帮助,请将其中一个主题传递给help
功能:
>>> help("TRUTHVALUE")
Truth Value Testing
*******************
Any object can be tested for truth value, for use in an "if" or
"while" condition or as operand of the Boolean operations below.
By default, an object is considered true unless its class defines
either a "__bool__()" method that returns "False" or a "__len__()"
method that returns zero, when called with the object. [1] Here are
most of the built-in objects considered false:
* constants defined to be false: "None" and "False"
* zero of any numeric type: "0", "0.0", "0j", "Decimal(0)",
"Fraction(0, 1)"
* empty sequences and collections: "''", "()", "[]", "{}", "set()",
"range(0)"
Operations and built-in functions that have a Boolean result always
return "0" or "False" for false and "1" or "True" for true, unless
otherwise stated. (Important exception: the Boolean operations "or"
and "and" always return one of their operands.)
Related help topics: if, while, and, or, not, BASICMETHODS
主题(Topics) 总是以大写字母拼写,以区别于 keywords, symbols 等。
元帮助Meta-help
想知道有哪些topics可以寻求帮助吗?请就 “topics “寻求帮助:
>>> help("topics")
Here is a list of available topics. Enter any topic name to get more help.
ASSERTION DELETION LOOPING SHIFTING
ASSIGNMENT DICTIONARIES MAPPINGMETHODS SLICINGS
ATTRIBUTEMETHODS DICTIONARYLITERALS MAPPINGS SPECIALATTRIBUTES
ATTRIBUTES DYNAMICFEATURES METHODS SPECIALIDENTIFIERS
AUGMENTEDASSIGNMENT ELLIPSIS MODULES SPECIALMETHODS
BASICMETHODS EXCEPTIONS NAMESPACES STRINGMETHODS
BINARY EXECUTION NONE STRINGS
BITWISE EXPRESSIONS NUMBERMETHODS SUBSCRIPTS
BOOLEAN FLOAT NUMBERS TRACEBACKS
CALLABLEMETHODS FORMATTING OBJECTS TRUTHVALUE
CALLS FRAMEOBJECTS OPERATORS TUPLELITERALS
CLASSES FRAMES PACKAGES TUPLES
CODEOBJECTS FUNCTIONS POWER TYPEOBJECTS
COMPARISON IDENTIFIERS PRECEDENCE TYPES
COMPLEX IMPORTING PRIVATENAMES UNARY
CONDITIONAL INTEGER RETURNING UNICODE
CONTEXTMANAGERS LISTLITERALS SCOPING
CONVERSIONS LISTS SEQUENCEMETHODS
DEBUGGING LITERALS SEQUENCES
要查看可以寻求帮助的符号,请将 “symbols “传给help
:
>>> help("symbols")
Here is a list of the punctuation symbols which Python assigns special meaning
to. Enter any symbol to get more help.
!= + <= __
" += <> `
""" , == b"
% - > b'
%= -= >= f"
& . >> f'
&= ... >>= j
' / @ r"
''' // J r'
( //= [ u"
) /= \ u'
* : ] |
** < ^ |=
**= << ^= ~
*= <<= _
同样的道理也适用于 “keywords”:
>>> help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
如果您请求 “modules “帮助,您还会看到所有已安装模块的列表,您可以就这些模块请求帮助:
>>> help("modules")
为了收集这些信息,Python 会导入它能找到的所有模块,因此在 Python 进程中首次运行 help(“modules”) 时,Python 通常需要一秒钟来发现并导入所有模块。
help实用程序
不确定您需要什么帮助?如果不带任何参数调用 help 函数,就会进入 “help 实用程序”。
>>> help()
Welcome to Python 3.13's help utility! If this is your first time using
Python, you should definitely check out the tutorial at
https://docs.python.org/3.13/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To get a list of available
modules, keywords, symbols, or topics, enter "modules", "keywords",
"symbols", or "topics".
Each module also comes with a one-line summary of what it does; to list
the modules whose name or summary contain a given string such as "spam",
enter "modules spam".
To quit this help utility and return to the interpreter,
enter "q", "quit" or "exit".
help>
注意:从 Python 3.13 开始,您可以键入不带括号的 help
来启动相同的工具。
在 help
工具中,您可以输入您想获得帮助的内容的名称。
您可以在 help>
提示符下提供帮助函数所接受的任何字符串,以查看相关文档。
你经常会发现字符串没有帮助。例如,函数就没有帮助:
help> functions
No Python documentation found for 'functions'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.
如果在帮助实用程序中键入help
,就会再次看到初始提示,其中指出 modules
, keywords
, symbols
, 和 topics
是最高级别的分类,可以用来发现help
可以接受的字符串:
help> help
Welcome to Python 3.13's help utility! If this is your first time using
Python, you should definitely check out the tutorial at
https://docs.python.org/3.13/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To get a list of available
modules, keywords, symbols, or topics, enter "modules", "keywords",
"symbols", or "topics".
Each module also comes with a one-line summary of what it does; to list
the modules whose name or summary contain a given string such as "spam",
enter "modules spam".
To quit this help utility and return to the interpreter,
enter "q", "quit" or "exit".
无法上网?您仍然可以获得help
!
既然有搜索引擎,为什么还要使用help
功能?
如果你被困在没有网络的地方几个小时,帮助功能会非常方便。
此外,如果您发现自己处于 Python REPL 或 PDB 会话中,并想知道某个对象是如何工作的,那么帮助对于反省对象也会非常方便。您可能还想了解一下用于反省 Python 对象的 type、dir 和 vars 函数。
有关如何在帮助输出中解读函数定义中使用的各种符号的更多信息,请参阅了解 Python 中的帮助。
你也许感兴趣的:
- Python 奇特的自引用
- 揭秘 Python 的 10 个隐藏技巧
- 如果您使用 Python… 你现在就需要了解这 3 个工具!
- 【外评】Python 为何如此糟糕…
- 【外评】用 Python 解释 Rust 背后的思想或理念
- Python 版本之间的主要变化摘要
- 【外评】Python 与苹果应用商店的拒绝作斗争
- 【外评】使用不安全的 Python 将速度提高 100 倍
- 谷歌裁掉整个 Python 团队!PyTorch 创始人急得直骂人:“WTF!核心语言团队无可替换”
- 谷歌Python团队全员被裁——负责内部Python所有基础设施、曾对数亿行代码执行自动重构
在获取符号帮助方面还有待改进:
help(“**”)解释了幂运算符,但也可以提及解包。
help(“<<”)没有提及位移(显示了 “运算符优先级 ”页面)。
我本来想说,语言应该强调符号的帮助,因为它们很难在谷歌上搜索到,但我想在 LLM 时代,这已经不再正确了。
同样是在方法签名中使用 /,却没有说明其含义。
这篇文章也没有。
显然,“它表示仅有位置参数的结束,即不能用作关键字参数的参数”。
这对大多数函数来说都是多余的,因为它们只有位置参数。
> 对大多数函数来说,这都是多余的,因为它们只有位置参数。
如果是这样的话,它就不需要存在了。
Python 的 “默认 ”参数既可以通过位置传递,也可以通过关键字传递。在 Python 3.8 之前,在纯 Python 中只有使用 *args 并自行解包才能获得位置参数。
为什么即使情况并非如此,它仍然需要存在?
阻止别人在传入参数时命名参数有什么好处?
阅读添加该参数的 PEP,它似乎主要是为了反映 C 内建函数一般不允许这样做的情况,以提高性能。
https://peps.python.org/pep-0570/#rationale
尽管如此,你还是可以在 Python 编写的模块中找到很多用途–不过我不会假装我可以告诉你所有这些用途的理由。
在我自己的代码中,我发现它们的主要用途是不在 kwargs 中 “保留 “插槽,这是完全有效的代码:
之前你可以用 dict 来解决这个问题,但现在能像正常情况一样接受 args 就友好多了。
我还真不知道 kwargs 这回事!非常有趣,也非常有用,这样就不会在这个层面上产生无意的冲突了。
> 阻止别人在传入参数时命名参数有什么好处?
在某些情况下,参数名称在调用方毫无价值,这在一元或二元函数中尤为常见。
在这种情况下,在调用站点命名参数的能力只是限制了实现和重载(在方法的情况下)。
没错。例如,像 max() 或 abs() 这样的方法就没有有意义的参数名。但例如 max() 也会使用一个名为 “key ”的参数。
当参数名对最终结果毫无意义时
函数返回的是天数的绝对差值,因此 date1、date2 是毫无意义的变量名。这样看起来就像引入了一个顺序(#1 是较早的日期,而#2 是较晚的日期?) 如果用户没有得到任何选项,那么很明显这个顺序是没有意义的
与之比较
请注意,现在
如果函数签名是 day_difference(date1,date2,*),则必须将参数指定为 kwargs,从而消除混淆:
编辑:这是错的,我把 “*”的想法混入了这个,是我的错。
— 原文如下
> 阻止别人在传入参数时命名参数有什么好处?
据我所知,这个功能主要用于相反的方向,即强制调用者使用超过一定数量(或为零)位置参数的关键字参数。
但那是 *,不是 /。
是的!
这不是多余的,因为即使没有默认值,列表中没有 / 的普通 python 参数也可以用名称调用。作者可能打算只使用位置参数,但有些调用者可能会以名称调用它们,而你在重构参数名时可能会破坏它们,位置参数可以避免这种情况。有些人不喜欢只使用位置参数,但用 c 编写的许多 stdlib 函数中已经使用了位置参数,因此在纯 Python 中编写具有相同语义的替换函数以及表达 c 函数的签名是有意义的。
这显然是不正确的。请看我上面的 math.sin 例子。
我的主要观点仍然有效。
1. 对于 help(math.sin) 这样的东西来说,它是无用的噪音。
2. 它无处不在,却没有很好的文档记录。这对于一个帮助系统来说真是讽刺!
该死的,Python 的帮助系统很难改进。Python2 没有 re.MatchObject 的条目。当我在 irc #python 上提到这个问题时,得到的回应是直接谷歌一下。help()应该能帮上忙。
对于类似 `help(math.sin)`这样的东西,它并不是无用的噪音。help 显示的签名是 `sin(x,/)`,它告诉你 `sin(x=1)`会失败。如果签名只是 `sin(x)`,`sin(x=1)` 就能正常工作。
好吧,你是对的。但在看到同胞的评论之前,我甚至没有想到要尝试 sin(x=2)。
我想那是因为你不知道函数参数在 python 中是如何工作的,但这并不是帮助文档的错。
令人吃惊。好像 help() 不能改进,这也不是什么 “错误”。
不过,help()不应该在你每次查找单个帮助主题时都重新教你语言的语法。尽管“/”的用法并不常见,但它似乎应该有自己的帮助主题。否则,这意味着 help() 必须重新解释每一个可能被视为 “不常用 ”的语法片段,这就很难划清界限了。
python 函数的默认值是 params 可以指定为位置或关键字。/ 使其前面的参数只能是位置参数,而 * 使其后面的参数只能是关键字。
哦,这个功能对我来说很新鲜。详见 PEP 570[1]。我个人认为这不是任何代码都应该做的……但我不是 BDFL!
1: https://peps.python.org/pep-0570/
有一种情况是非常可取的:
但是,正如 PEP 所指出的,有时你只是不想让参数名成为公共合同的一部分,有一种表达方式就好了。
> 这对大多数函数来说都是多余的,因为它们只有位置参数。
是吗?不是这样的。
This can be invoked as either `foo(1, 2, 3)` or `foo(c=3, b=2, a=1)`:
/ 无处不在,但通常只是噪音。无法解释的噪音。
它通常用于内置程序,因为在 Python/C API 中,模仿 Python 默认的通过位置和名称接受参数的行为是很麻烦的。(只接受位置参数也有其他用例,例如同时接受一个任意函数和一组任意参数来调用它–例如,在一个新的 coroutine 中调用它–但这种情况很少见)。大多数内置函数的这种特殊性早在 Python 3 出现之前就已经存在了,只是在引入这种语法之前没有被记录下来,而且很难在 Python 中仿效。
至于没有解释的噪音–嗯,函数声明语法的所有其他部分也没有解释。你应该知道函数声明的语法,才能阅读关于单个函数声明的帮助;这就是语法参考的作用。
你如何通过 repl help() 系统发现语法参考?
找到了。
>>> help(‘def’)
如果使用 Vim,SHIFT+K 会显示光标下对象的帮助文档。如果你想从 `object.method` 中获得 `method` 的帮助,只需选中 `object.method`,然后按 SHIFT+K。
这种导航方式有点笨拙,但对于在缓冲区中快速进行一次性操作来说却非常方便。
谢谢,超级方便
不错。我通常会把 dir() 作为我在命令行下的第一个检查工具。
或者它的两个好朋友:locals() 和 globals(),可以同时查看它们的名称和值;当你在生产中只能通过日志记录器来了解情况时,我用它作为伪调试器已经获得了很多益处
不要忘记 `vars()`。
我以前也这样做,但 wat 提供了更好的方法打印输出:https://github.com/igrek51/wat
我来回跳来跳去。先是 dir() 然后是 help()…
vars() 是另一个很好的方法,如果你要查找具有特定值的内容的话。
help() 也很不错,但我最喜欢的从 Python REPL 快速获取对象信息的工具还是 wat。
只需`pip install wat`,然后如果您需要某个对象 o 的信息,执行`wat / o`。如果需要完整的文档说明,则执行 `wat.long / o` 。
当你使用一个文档不全的软件包时,它是你的救星。
亲爱的上帝:https://github.com/igrek51/wat?tab=readme-ov-file#load-from-…
我一直认为 python 是更易读的 perl 版本。我最初是从 “import this ”语句中得到这种印象的。
字形片段中的加载与我的理解一致。
声明一下,这不是我认为的成语 Python。
网页的样式表被破坏了(返回 HTTP 404),但文本仍然相当可读。干得好
> 还有其他方法可以使用帮助函数,但在我们深入研究之前,我想先讨论一下上面输出中显示的 * 和 / 符号。
这个问题在哪里解决?这里缺少哪一部分吗?
我发布这个是因为我总是忘记是哪一个,而且搜索它几乎是不可能的。
https://peps.python.org/pep-0457/#syntax-and-semantics
/“标记了 ”仅限位置 “和 ”混合 “的边界,然后 ”*“也标记了 ”混合 “和 ”仅限 kwargs “的边界。
一个有趣的副作用是,它可以运行您导入的模块内的代码,因此代码可以根据是否被帮助导入进行操作:
https://tio.run/##VY6/DoIwEMb3PsUXl6ODLK7ETVcfwBhylBqIpW1KB3…
为了快速查找,我通常使用 pydoc[1],它能显示大致相同的帮助字符串,但无需进入 repl。我认为有几个类似的 *doc 函数。我能想到的有 texdoc(通常只打开软件包文档的 pdf 版)和 perldoc。
pydoc -b 作为标准的库参考资料也非常有用,当你没有连接到互联网,并且你可以忍受相当有趣的默认配色方案时。
[1] https://docs.python.org/3/library/pydoc.html
3.13 之前:https://thejenkinscomic.net/?id=52
好主意。其他语言有这个功能吗?
R 的帮助功能可能是所有语言中最好的 — 你不仅可以用“? ”来询问单个函数的帮助,而且传统上(大多数附加软件包和内置软件也是如此),它不仅会提供函数的信息,还会提供使用该函数的示例代码,以便你了解它的实际作用。
Ruby 也有类似的 help() 函数,您可以在 REPL (irb) 中调用,也可以使用独立工具 `ri`[1] 在 CLI 中调用。该功能非常实用!
[1]: https://stackoverflow.com/a/25671404
Clojure 有文档和源代码函数。例如
和这里的许多人一样,我曾经用 golang 写过一个玩具 lisp,并添加了一个帮助函数。它将提供所有内置函数的使用信息。
用于 ocaml 的 utop 很酷,它提供函数的类型签名,没有明确的帮助,但可以用 tab 提供补全。
与此类似,rtop 也可用于 reason。
https://opam.ocaml.org/blog/about-utop/ 和 https://opam.ocaml.org/packages/rtop/
我写了一个添加 `#doc List.find` 指令的小工具。不过,我已经不再维护它了,因为我觉得它的使用率并不高,而且要跟上 OCaml 编译器内部的变化也很费事(我的印象是它从未得到广泛采用)。https://github.com/reynir/ocp-index-top。
dbuenzli 的 down 也有类似功能。
虽然 Mathematica 可能不是很多人(包括我自己)心目中最喜欢的编程语言,但它确实有非常棒的帮助,可以使用 `?`进行访问,并可根据需要进行扩展。
到目前为止,Smalltalk 是此类语言中的佼佼者。