### 导航
- [索引](../genindex.xhtml "总目录")
- [模块](../py-modindex.xhtml "Python 模块索引") |
- [下一页](unittest.xhtml "unittest --- 单元测试框架") |
- [上一页](pydoc.xhtml "pydoc --- Documentation generator and online help system") |
- ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png)
- [Python](https://www.python.org/) »
- zh\_CN 3.7.3 [文档](../index.xhtml) »
- [Python 标准库](index.xhtml) »
- [开发工具](development.xhtml) »
- $('.inline-search').show(0); |
# [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.") --- Test interactive Python examples
**Source code:** [Lib/doctest.py](https://github.com/python/cpython/tree/3.7/Lib/doctest.py) \[https://github.com/python/cpython/tree/3.7/Lib/doctest.py\]
- - - - - -
The [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.") module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown. There are several common ways to use doctest:
- To check that a module's docstrings are up-to-date by verifying that all interactive examples still work as documented.
- To perform regression testing by verifying that interactive examples from a test file or a test object work as expected.
- To write tutorial documentation for a package, liberally illustrated with input-output examples. Depending on whether the examples or the expository text are emphasized, this has the flavor of "literate testing" or "executable documentation".
Here's a complete but small example module:
```
"""
This is the "example" module.
The example module supplies one function, factorial(). For example,
>>> factorial(5)
120
"""
def factorial(n):
"""Return the factorial of n, an exact integer >= 0.
>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(30)
265252859812191058636308480000000
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0
Factorials of floats are OK, but the float must be an exact integer:
>>> factorial(30.1)
Traceback (most recent call last):
...
ValueError: n must be exact integer
>>> factorial(30.0)
265252859812191058636308480000000
It must also not be ridiculously large:
>>> factorial(1e100)
Traceback (most recent call last):
...
OverflowError: n too large
"""
import math
if not n >= 0:
raise ValueError("n must be >= 0")
if math.floor(n) != n:
raise ValueError("n must be exact integer")
if n+1 == n: # catch a value like 1e300
raise OverflowError("n too large")
result = 1
factor = 2
while factor <= n:
result *= factor
factor += 1
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
```
If you run `example.py` directly from the command line, [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.")works its magic:
```
$ python example.py
$
```
There's no output! That's normal, and it means all the examples worked. Pass `-v` to the script, and [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.") prints a detailed log of what it's trying, and prints a summary at the end:
```
$ python example.py -v
Trying:
factorial(5)
Expecting:
120
ok
Trying:
[factorial(n) for n in range(6)]
Expecting:
[1, 1, 2, 6, 24, 120]
ok
```
And so on, eventually ending with:
```
Trying:
factorial(1e100)
Expecting:
Traceback (most recent call last):
...
OverflowError: n too large
ok
2 items passed all tests:
1 tests in __main__
8 tests in __main__.factorial
9 tests in 2 items.
9 passed and 0 failed.
Test passed.
$
```
That's all you need to know to start making productive use of [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.")! Jump in. The following sections provide full details. Note that there are many examples of doctests in the standard Python test suite and libraries. Especially useful examples can be found in the standard test file `Lib/test/test_doctest.py`.
## Simple Usage: Checking Examples in Docstrings
The simplest way to start using doctest (but not necessarily the way you'll continue to do it) is to end each module `M` with:
```
if __name__ == "__main__":
import doctest
doctest.testmod()
```
[`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.") then examines docstrings in module `M`.
Running the module as a script causes the examples in the docstrings to get executed and verified:
```
python M.py
```
This won't display anything unless an example fails, in which case the failing example(s) and the cause(s) of the failure(s) are printed to stdout, and the final line of output is `***Test Failed*** N failures.`, where *N* is the number of examples that failed.
Run it with the `-v` switch instead:
```
python M.py -v
```
and a detailed report of all examples tried is printed to standard output, along with assorted summaries at the end.
You can force verbose mode by passing `verbose=True` to [`testmod()`](#doctest.testmod "doctest.testmod"), or prohibit it by passing `verbose=False`. In either of those cases, `sys.argv` is not examined by [`testmod()`](#doctest.testmod "doctest.testmod") (so passing `-v` or not has no effect).
There is also a command line shortcut for running [`testmod()`](#doctest.testmod "doctest.testmod"). You can instruct the Python interpreter to run the doctest module directly from the standard library and pass the module name(s) on the command line:
```
python -m doctest -v example.py
```
This will import `example.py` as a standalone module and run [`testmod()`](#doctest.testmod "doctest.testmod") on it. Note that this may not work correctly if the file is part of a package and imports other submodules from that package.
For more information on [`testmod()`](#doctest.testmod "doctest.testmod"), see section [Basic API](#doctest-basic-api).
## Simple Usage: Checking Examples in a Text File
Another simple application of doctest is testing interactive examples in a text file. This can be done with the [`testfile()`](#doctest.testfile "doctest.testfile") function:
```
import doctest
doctest.testfile("example.txt")
```
That short script executes and verifies any interactive Python examples contained in the file `example.txt`. The file content is treated as if it were a single giant docstring; the file doesn't need to contain a Python program! For example, perhaps `example.txt` contains this:
```
The ``example`` module
======================
Using ``factorial``
-------------------
This is an example text file in reStructuredText format. First import
``factorial`` from the ``example`` module:
>>> from example import factorial
Now use it:
>>> factorial(6)
120
```
Running `doctest.testfile("example.txt")` then finds the error in this documentation:
```
File "./example.txt", line 14, in example.txt
Failed example:
factorial(6)
Expected:
120
Got:
720
```
As with [`testmod()`](#doctest.testmod "doctest.testmod"), [`testfile()`](#doctest.testfile "doctest.testfile") won't display anything unless an example fails. If an example does fail, then the failing example(s) and the cause(s) of the failure(s) are printed to stdout, using the same format as [`testmod()`](#doctest.testmod "doctest.testmod").
By default, [`testfile()`](#doctest.testfile "doctest.testfile") looks for files in the calling module's directory. See section [Basic API](#doctest-basic-api) for a description of the optional arguments that can be used to tell it to look for files in other locations.
Like [`testmod()`](#doctest.testmod "doctest.testmod"), [`testfile()`](#doctest.testfile "doctest.testfile")'s verbosity can be set with the `-v` command-line switch or with the optional keyword argument *verbose*.
There is also a command line shortcut for running [`testfile()`](#doctest.testfile "doctest.testfile"). You can instruct the Python interpreter to run the doctest module directly from the standard library and pass the file name(s) on the command line:
```
python -m doctest -v example.txt
```
Because the file name does not end with `.py`, [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.") infers that it must be run with [`testfile()`](#doctest.testfile "doctest.testfile"), not [`testmod()`](#doctest.testmod "doctest.testmod").
For more information on [`testfile()`](#doctest.testfile "doctest.testfile"), see section [Basic API](#doctest-basic-api).
## How It Works
This section examines in detail how doctest works: which docstrings it looks at, how it finds interactive examples, what execution context it uses, how it handles exceptions, and how option flags can be used to control its behavior. This is the information that you need to know to write doctest examples; for information about actually running doctest on these examples, see the following sections.
### Which Docstrings Are Examined?
The module docstring, and all function, class and method docstrings are searched. Objects imported into the module are not searched.
In addition, if `M.__test__` exists and "is true", it must be a dict, and each entry maps a (string) name to a function object, class object, or string. Function and class object docstrings found from `M.__test__` are searched, and strings are treated as if they were docstrings. In output, a key `K` in `M.__test__` appears with name
```
<name of M>.__test__.K
```
Any classes found are recursively searched similarly, to test docstrings in their contained methods and nested classes.
**CPython implementation detail:** Prior to version 3.4, extension modules written in C were not fully searched by doctest.
### How are Docstring Examples Recognized?
In most cases a copy-and-paste of an interactive console session works fine, but doctest isn't trying to do an exact emulation of any specific Python shell.
```
>>> # comments are ignored
>>> x = 12
>>> x
12
>>> if x == 13:
... print("yes")
... else:
... print("no")
... print("NO")
... print("NO!!!")
...
no
NO
NO!!!
>>>
```
Any expected output must immediately follow the final `'>>> '` or `'... '`line containing the code, and the expected output (if any) extends to the next `'>>> '` or all-whitespace line.
The fine print:
- Expected output cannot contain an all-whitespace line, since such a line is taken to signal the end of expected output. If expected output does contain a blank line, put `<BLANKLINE>` in your doctest example each place a blank line is expected.
- All hard tab characters are expanded to spaces, using 8-column tab stops. Tabs in output generated by the tested code are not modified. Because any hard tabs in the sample output *are* expanded, this means that if the code output includes hard tabs, the only way the doctest can pass is if the [`NORMALIZE_WHITESPACE`](#doctest.NORMALIZE_WHITESPACE "doctest.NORMALIZE_WHITESPACE") option or [directive](#doctest-directives)is in effect. Alternatively, the test can be rewritten to capture the output and compare it to an expected value as part of the test. This handling of tabs in the source was arrived at through trial and error, and has proven to be the least error prone way of handling them. It is possible to use a different algorithm for handling tabs by writing a custom [`DocTestParser`](#doctest.DocTestParser "doctest.DocTestParser") class.
- Output to stdout is captured, but not output to stderr (exception tracebacks are captured via a different means).
- If you continue a line via backslashing in an interactive session, or for any other reason use a backslash, you should use a raw docstring, which will preserve your backslashes exactly as you type them:
```
>>> def f(x):
... r'''Backslashes in a raw docstring: m\n'''
>>> print(f.__doc__)
Backslashes in a raw docstring: m\n
```
Otherwise, the backslash will be interpreted as part of the string. For example, the `\n` above would be interpreted as a newline character. Alternatively, you can double each backslash in the doctest version (and not use a raw string):
```
>>> def f(x):
... '''Backslashes in a raw docstring: m\\n'''
>>> print(f.__doc__)
Backslashes in a raw docstring: m\n
```
- The starting column doesn't matter:
```
>>> assert "Easy!"
>>> import math
>>> math.floor(1.9)
1
```
and as many leading whitespace characters are stripped from the expected output as appeared in the initial `'>>> '` line that started the example.
### What's the Execution Context?
By default, each time [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.") finds a docstring to test, it uses a *shallow copy* of `M`'s globals, so that running tests doesn't change the module's real globals, and so that one test in `M` can't leave behind crumbs that accidentally allow another test to work. This means examples can freely use any names defined at top-level in `M`, and names defined earlier in the docstring being run. Examples cannot see names defined in other docstrings.
You can force use of your own dict as the execution context by passing `globs=your_dict` to [`testmod()`](#doctest.testmod "doctest.testmod") or [`testfile()`](#doctest.testfile "doctest.testfile") instead.
### What About Exceptions?
No problem, provided that the traceback is the only output produced by the example: just paste in the traceback. [1](#id2) Since tracebacks contain details that are likely to change rapidly (for example, exact file paths and line numbers), this is one case where doctest works hard to be flexible in what it accepts.
Simple example:
```
>>> [1, 2, 3].remove(42)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
```
That doctest succeeds if [`ValueError`](exceptions.xhtml#ValueError "ValueError") is raised, with the
```
list.remove(x):
x not in list
```
detail as shown.
The expected output for an exception must start with a traceback header, which may be either of the following two lines, indented the same as the first line of the example:
```
Traceback (most recent call last):
Traceback (innermost last):
```
The traceback header is followed by an optional traceback stack, whose contents are ignored by doctest. The traceback stack is typically omitted, or copied verbatim from an interactive session.
The traceback stack is followed by the most interesting part: the line(s) containing the exception type and detail. This is usually the last line of a traceback, but can extend across multiple lines if the exception has a multi-line detail:
```
>>> raise ValueError('multi\n line\ndetail')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: multi
line
detail
```
The last three lines (starting with [`ValueError`](exceptions.xhtml#ValueError "ValueError")) are compared against the exception's type and detail, and the rest are ignored.
Best practice is to omit the traceback stack, unless it adds significant documentation value to the example. So the last example is probably better as:
```
>>> raise ValueError('multi\n line\ndetail')
Traceback (most recent call last):
...
ValueError: multi
line
detail
```
Note that tracebacks are treated very specially. In particular, in the rewritten example, the use of `...` is independent of doctest's [`ELLIPSIS`](#doctest.ELLIPSIS "doctest.ELLIPSIS") option. The ellipsis in that example could be left out, or could just as well be three (or three hundred) commas or digits, or an indented transcript of a Monty Python skit.
Some details you should read once, but won't need to remember:
- Doctest can't guess whether your expected output came from an exception traceback or from ordinary printing. So, e.g., an example that expects `ValueError: 42 is prime` will pass whether [`ValueError`](exceptions.xhtml#ValueError "ValueError") is actually raised or if the example merely prints that traceback text. In practice, ordinary output rarely begins with a traceback header line, so this doesn't create real problems.
- Each line of the traceback stack (if present) must be indented further than the first line of the example, *or* start with a non-alphanumeric character. The first line following the traceback header indented the same and starting with an alphanumeric is taken to be the start of the exception detail. Of course this does the right thing for genuine tracebacks.
- When the [`IGNORE_EXCEPTION_DETAIL`](#doctest.IGNORE_EXCEPTION_DETAIL "doctest.IGNORE_EXCEPTION_DETAIL") doctest option is specified, everything following the leftmost colon and any module information in the exception name is ignored.
- The interactive shell omits the traceback header line for some [`SyntaxError`](exceptions.xhtml#SyntaxError "SyntaxError")s. But doctest uses the traceback header line to distinguish exceptions from non-exceptions. So in the rare case where you need to test a [`SyntaxError`](exceptions.xhtml#SyntaxError "SyntaxError") that omits the traceback header, you will need to manually add the traceback header line to your test example.
- For some [`SyntaxError`](exceptions.xhtml#SyntaxError "SyntaxError")s, Python displays the character position of the syntax error, using a `^` marker:
```
>>> 1 1
File "<stdin>", line 1
1 1
^
SyntaxError: invalid syntax
```
Since the lines showing the position of the error come before the exception type and detail, they are not checked by doctest. For example, the following test would pass, even though it puts the `^` marker in the wrong location:
```
>>> 1 1
File "<stdin>", line 1
1 1
^
SyntaxError: invalid syntax
```
### Option Flags
A number of option flags control various aspects of doctest's behavior. Symbolic names for the flags are supplied as module constants, which can be [bitwise ORed](../reference/expressions.xhtml#bitwise) together and passed to various functions. The names can also be used in [doctest directives](#doctest-directives), and may be passed to the doctest command line interface via the `-o` option.
3\.4 新版功能: The `-o` command line option.
The first group of options define test semantics, controlling aspects of how doctest decides whether actual output matches an example's expected output:
`doctest.``DONT_ACCEPT_TRUE_FOR_1`By default, if an expected output block contains just `1`, an actual output block containing just `1` or just `True` is considered to be a match, and similarly for `0` versus `False`. When [`DONT_ACCEPT_TRUE_FOR_1`](#doctest.DONT_ACCEPT_TRUE_FOR_1 "doctest.DONT_ACCEPT_TRUE_FOR_1") is specified, neither substitution is allowed. The default behavior caters to that Python changed the return type of many functions from integer to boolean; doctests expecting "little integer" output still work in these cases. This option will probably go away, but not for several years.
`doctest.``DONT_ACCEPT_BLANKLINE`By default, if an expected output block contains a line containing only the string `<BLANKLINE>`, then that line will match a blank line in the actual output. Because a genuinely blank line delimits the expected output, this is the only way to communicate that a blank line is expected. When [`DONT_ACCEPT_BLANKLINE`](#doctest.DONT_ACCEPT_BLANKLINE "doctest.DONT_ACCEPT_BLANKLINE") is specified, this substitution is not allowed.
`doctest.``NORMALIZE_WHITESPACE`When specified, all sequences of whitespace (blanks and newlines) are treated as equal. Any sequence of whitespace within the expected output will match any sequence of whitespace within the actual output. By default, whitespace must match exactly. [`NORMALIZE_WHITESPACE`](#doctest.NORMALIZE_WHITESPACE "doctest.NORMALIZE_WHITESPACE") is especially useful when a line of expected output is very long, and you want to wrap it across multiple lines in your source.
`doctest.``ELLIPSIS`When specified, an ellipsis marker (`...`) in the expected output can match any substring in the actual output. This includes substrings that span line boundaries, and empty substrings, so it's best to keep usage of this simple. Complicated uses can lead to the same kinds of "oops, it matched too much!" surprises that `.*` is prone to in regular expressions.
`doctest.``IGNORE_EXCEPTION_DETAIL`When specified, an example that expects an exception passes if an exception of the expected type is raised, even if the exception detail does not match. For example, an example expecting `ValueError: 42` will pass if the actual exception raised is `ValueError: 3*14`, but will fail, e.g., if [`TypeError`](exceptions.xhtml#TypeError "TypeError") is raised.
It will also ignore the module name used in Python 3 doctest reports. Hence both of these variations will work with the flag specified, regardless of whether the test is run under Python 2.7 or Python 3.2 (or later versions):
```
>>> raise CustomError('message')
Traceback (most recent call last):
CustomError: message
>>> raise CustomError('message')
Traceback (most recent call last):
my_module.CustomError: message
```
Note that [`ELLIPSIS`](#doctest.ELLIPSIS "doctest.ELLIPSIS") can also be used to ignore the details of the exception message, but such a test may still fail based on whether or not the module details are printed as part of the exception name. Using [`IGNORE_EXCEPTION_DETAIL`](#doctest.IGNORE_EXCEPTION_DETAIL "doctest.IGNORE_EXCEPTION_DETAIL") and the details from Python 2.3 is also the only clear way to write a doctest that doesn't care about the exception detail yet continues to pass under Python 2.3 or earlier (those releases do not support [doctest directives](#doctest-directives) and ignore them as irrelevant comments). For example:
```
>>> (1, 2)[3] = 'moo'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object doesn't support item assignment
```
passes under Python 2.3 and later Python versions with the flag specified, even though the detail changed in Python 2.4 to say "does not" instead of "doesn't".
在 3.2 版更改: [`IGNORE_EXCEPTION_DETAIL`](#doctest.IGNORE_EXCEPTION_DETAIL "doctest.IGNORE_EXCEPTION_DETAIL") now also ignores any information relating to the module containing the exception under test.
`doctest.``SKIP`When specified, do not run the example at all. This can be useful in contexts where doctest examples serve as both documentation and test cases, and an example should be included for documentation purposes, but should not be checked. E.g., the example's output might be random; or the example might depend on resources which would be unavailable to the test driver.
The SKIP flag can also be used for temporarily "commenting out" examples.
`doctest.``COMPARISON_FLAGS`A bitmask or'ing together all the comparison flags above.
The second group of options controls how test failures are reported:
`doctest.``REPORT_UDIFF`When specified, failures that involve multi-line expected and actual outputs are displayed using a unified diff.
`doctest.``REPORT_CDIFF`When specified, failures that involve multi-line expected and actual outputs will be displayed using a context diff.
`doctest.``REPORT_NDIFF`When specified, differences are computed by `difflib.Differ`, using the same algorithm as the popular `ndiff.py` utility. This is the only method that marks differences within lines as well as across lines. For example, if a line of expected output contains digit `1` where actual output contains letter `l`, a line is inserted with a caret marking the mismatching column positions.
`doctest.``REPORT_ONLY_FIRST_FAILURE`When specified, display the first failing example in each doctest, but suppress output for all remaining examples. This will prevent doctest from reporting correct examples that break because of earlier failures; but it might also hide incorrect examples that fail independently of the first failure. When [`REPORT_ONLY_FIRST_FAILURE`](#doctest.REPORT_ONLY_FIRST_FAILURE "doctest.REPORT_ONLY_FIRST_FAILURE") is specified, the remaining examples are still run, and still count towards the total number of failures reported; only the output is suppressed.
`doctest.``FAIL_FAST`When specified, exit after the first failing example and don't attempt to run the remaining examples. Thus, the number of failures reported will be at most 1. This flag may be useful during debugging, since examples after the first failure won't even produce debugging output.
The doctest command line accepts the option `-f` as a shorthand for
```
-o
FAIL_FAST
```
.
3\.4 新版功能.
`doctest.``REPORTING_FLAGS`A bitmask or'ing together all the reporting flags above.
There is also a way to register new option flag names, though this isn't useful unless you intend to extend [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.") internals via subclassing:
`doctest.``register_optionflag`(*name*)Create a new option flag with a given name, and return the new flag's integer value. [`register_optionflag()`](#doctest.register_optionflag "doctest.register_optionflag") can be used when subclassing [`OutputChecker`](#doctest.OutputChecker "doctest.OutputChecker") or [`DocTestRunner`](#doctest.DocTestRunner "doctest.DocTestRunner") to create new options that are supported by your subclasses. [`register_optionflag()`](#doctest.register_optionflag "doctest.register_optionflag") should always be called using the following idiom:
```
MY_FLAG = register_optionflag('MY_FLAG')
```
### Directives
Doctest directives may be used to modify the [option flags](#doctest-options) for an individual example. Doctest directives are special Python comments following an example's source code:
```
directive ::= "#" "doctest:" directive_options
directive_options ::= directive_option ("," directive_option)\*
directive_option ::= on_or_off directive_option_name
on_or_off ::= "+" \| "-"
directive_option_name ::= "DONT_ACCEPT_BLANKLINE" \| "NORMALIZE_WHITESPACE" \| ...
```
Whitespace is not allowed between the `+` or `-` and the directive option name. The directive option name can be any of the option flag names explained above.
An example's doctest directives modify doctest's behavior for that single example. Use `+` to enable the named behavior, or `-` to disable it.
For example, this test passes:
```
>>> print(list(range(20)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
```
Without the directive it would fail, both because the actual output doesn't have two blanks before the single-digit list elements, and because the actual output is on a single line. This test also passes, and also requires a directive to do so:
```
>>> print(list(range(20)))
[0, 1, ..., 18, 19]
```
Multiple directives can be used on a single physical line, separated by commas:
```
>>> print(list(range(20)))
[0, 1, ..., 18, 19]
```
If multiple directive comments are used for a single example, then they are combined:
```
>>> print(list(range(20)))
...
[0, 1, ..., 18, 19]
```
As the previous example shows, you can add `...` lines to your example containing only directives. This can be useful when an example is too long for a directive to comfortably fit on the same line:
```
>>> print(list(range(5)) + list(range(10, 20)) + list(range(30, 40)))
...
[0, ..., 4, 10, ..., 19, 30, ..., 39]
```
Note that since all options are disabled by default, and directives apply only to the example they appear in, enabling options (via `+` in a directive) is usually the only meaningful choice. However, option flags can also be passed to functions that run doctests, establishing different defaults. In such cases, disabling an option via `-` in a directive can be useful.
### 警告
[`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.") is serious about requiring exact matches in expected output. If even a single character doesn't match, the test fails. This will probably surprise you a few times, as you learn exactly what Python does and doesn't guarantee about output. For example, when printing a set, Python doesn't guarantee that the element is printed in any particular order, so a test like
```
>>> foo()
{"Hermione", "Harry"}
```
is vulnerable! One workaround is to do
```
>>> foo() == {"Hermione", "Harry"}
True
```
instead. Another is to do
```
>>> d = sorted(foo())
>>> d
['Harry', 'Hermione']
```
注解
Before Python 3.6, when printing a dict, Python did not guarantee that the key-value pairs was printed in any particular order.
There are others, but you get the idea.
Another bad idea is to print things that embed an object address, like
```
>>> id(1.0) # certain to fail some of the time
7948648
>>> class C: pass
>>> C() # the default repr() for instances embeds an address
<__main__.C instance at 0x00AC18F0>
```
The [`ELLIPSIS`](#doctest.ELLIPSIS "doctest.ELLIPSIS") directive gives a nice approach for the last example:
```
>>> C()
<__main__.C instance at 0x...>
```
Floating-point numbers are also subject to small output variations across platforms, because Python defers to the platform C library for float formatting, and C libraries vary widely in quality here.
```
>>> 1./7 # risky
0.14285714285714285
>>> print(1./7) # safer
0.142857142857
>>> print(round(1./7, 6)) # much safer
0.142857
```
Numbers of the form `I/2.**J` are safe across all platforms, and I often contrive doctest examples to produce numbers of that form:
```
>>> 3./4 # utterly safe
0.75
```
Simple fractions are also easier for people to understand, and that makes for better documentation.
## Basic API
The functions [`testmod()`](#doctest.testmod "doctest.testmod") and [`testfile()`](#doctest.testfile "doctest.testfile") provide a simple interface to doctest that should be sufficient for most basic uses. For a less formal introduction to these two functions, see sections [Simple Usage: Checking Examples in Docstrings](#doctest-simple-testmod)and [Simple Usage: Checking Examples in a Text File](#doctest-simple-testfile).
`doctest.``testfile`(*filename*, *module\_relative=True*, *name=None*, *package=None*, *globs=None*, *verbose=None*, *report=True*, *optionflags=0*, *extraglobs=None*, *raise\_on\_error=False*, *parser=DocTestParser()*, *encoding=None*)All arguments except *filename* are optional, and should be specified in keyword form.
Test examples in the file named *filename*. Return
```
(failure_count,
test_count)
```
.
Optional argument *module\_relative* specifies how the filename should be interpreted:
- If *module\_relative* is `True` (the default), then *filename* specifies an OS-independent module-relative path. By default, this path is relative to the calling module's directory; but if the *package* argument is specified, then it is relative to that package. To ensure OS-independence, *filename* should use `/` characters to separate path segments, and may not be an absolute path (i.e., it may not begin with `/`).
- If *module\_relative* is `False`, then *filename* specifies an OS-specific path. The path may be absolute or relative; relative paths are resolved with respect to the current working directory.
Optional argument *name* gives the name of the test; by default, or if `None`, `os.path.basename(filename)` is used.
Optional argument *package* is a Python package or the name of a Python package whose directory should be used as the base directory for a module-relative filename. If no package is specified, then the calling module's directory is used as the base directory for module-relative filenames. It is an error to specify *package* if *module\_relative* is `False`.
Optional argument *globs* gives a dict to be used as the globals when executing examples. A new shallow copy of this dict is created for the doctest, so its examples start with a clean slate. By default, or if `None`, a new empty dict is used.
Optional argument *extraglobs* gives a dict merged into the globals used to execute examples. This works like [`dict.update()`](stdtypes.xhtml#dict.update "dict.update"): if *globs* and *extraglobs* have a common key, the associated value in *extraglobs* appears in the combined dict. By default, or if `None`, no extra globals are used. This is an advanced feature that allows parameterization of doctests. For example, a doctest can be written for a base class, using a generic name for the class, then reused to test any number of subclasses by passing an *extraglobs* dict mapping the generic name to the subclass to be tested.
Optional argument *verbose* prints lots of stuff if true, and prints only failures if false; by default, or if `None`, it's true if and only if `'-v'`is in `sys.argv`.
Optional argument *report* prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else the summary is very brief (in fact, empty if all tests passed).
Optional argument *optionflags* (default value 0) takes the [bitwise OR](../reference/expressions.xhtml#bitwise) of option flags. See section [Option Flags](#doctest-options).
Optional argument *raise\_on\_error* defaults to false. If true, an exception is raised upon the first failure or unexpected exception in an example. This allows failures to be post-mortem debugged. Default behavior is to continue running examples.
Optional argument *parser* specifies a [`DocTestParser`](#doctest.DocTestParser "doctest.DocTestParser") (or subclass) that should be used to extract tests from the files. It defaults to a normal parser (i.e., `DocTestParser()`).
Optional argument *encoding* specifies an encoding that should be used to convert the file to unicode.
`doctest.``testmod`(*m=None*, *name=None*, *globs=None*, *verbose=None*, *report=True*, *optionflags=0*, *extraglobs=None*, *raise\_on\_error=False*, *exclude\_empty=False*)All arguments are optional, and all except for *m* should be specified in keyword form.
Test examples in docstrings in functions and classes reachable from module *m*(or module [`__main__`](__main__.xhtml#module-__main__ "__main__: The environment where the top-level script is run.") if *m* is not supplied or is `None`), starting with `m.__doc__`.
Also test examples reachable from dict `m.__test__`, if it exists and is not `None`. `m.__test__` maps names (strings) to functions, classes and strings; function and class docstrings are searched for examples; strings are searched directly, as if they were docstrings.
Only docstrings attached to objects belonging to module *m* are searched.
Return `(failure_count, test_count)`.
Optional argument *name* gives the name of the module; by default, or if `None`, `m.__name__` is used.
Optional argument *exclude\_empty* defaults to false. If true, objects for which no doctests are found are excluded from consideration. The default is a backward compatibility hack, so that code still using `doctest.master.summarize()` in conjunction with [`testmod()`](#doctest.testmod "doctest.testmod") continues to get output for objects with no tests. The *exclude\_empty* argument to the newer [`DocTestFinder`](#doctest.DocTestFinder "doctest.DocTestFinder")constructor defaults to true.
Optional arguments *extraglobs*, *verbose*, *report*, *optionflags*, *raise\_on\_error*, and *globs* are the same as for function [`testfile()`](#doctest.testfile "doctest.testfile")above, except that *globs* defaults to `m.__dict__`.
`doctest.``run_docstring_examples`(*f*, *globs*, *verbose=False*, *name="NoName"*, *compileflags=None*, *optionflags=0*)Test examples associated with object *f*; for example, *f* may be a string, a module, a function, or a class object.
A shallow copy of dictionary argument *globs* is used for the execution context.
Optional argument *name* is used in failure messages, and defaults to `"NoName"`.
If optional argument *verbose* is true, output is generated even if there are no failures. By default, output is generated only in case of an example failure.
Optional argument *compileflags* gives the set of flags that should be used by the Python compiler when running the examples. By default, or if `None`, flags are deduced corresponding to the set of future features found in *globs*.
Optional argument *optionflags* works as for function [`testfile()`](#doctest.testfile "doctest.testfile") above.
## Unittest API
As your collection of doctest'ed modules grows, you'll want a way to run all their doctests systematically. [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.") provides two functions that can be used to create [`unittest`](unittest.xhtml#module-unittest "unittest: Unit testing framework for Python.") test suites from modules and text files containing doctests. To integrate with [`unittest`](unittest.xhtml#module-unittest "unittest: Unit testing framework for Python.") test discovery, include a `load_tests()` function in your test module:
```
import unittest
import doctest
import my_module_with_doctests
def load_tests(loader, tests, ignore):
tests.addTests(doctest.DocTestSuite(my_module_with_doctests))
return tests
```
There are two main functions for creating [`unittest.TestSuite`](unittest.xhtml#unittest.TestSuite "unittest.TestSuite") instances from text files and modules with doctests:
`doctest.``DocFileSuite`(*\*paths*, *module\_relative=True*, *package=None*, *setUp=None*, *tearDown=None*, *globs=None*, *optionflags=0*, *parser=DocTestParser()*, *encoding=None*)Convert doctest tests from one or more text files to a [`unittest.TestSuite`](unittest.xhtml#unittest.TestSuite "unittest.TestSuite").
The returned [`unittest.TestSuite`](unittest.xhtml#unittest.TestSuite "unittest.TestSuite") is to be run by the unittest framework and runs the interactive examples in each file. If an example in any file fails, then the synthesized unit test fails, and a `failureException`exception is raised showing the name of the file containing the test and a (sometimes approximate) line number.
Pass one or more paths (as strings) to text files to be examined.
Options may be provided as keyword arguments:
Optional argument *module\_relative* specifies how the filenames in *paths*should be interpreted:
- If *module\_relative* is `True` (the default), then each filename in *paths* specifies an OS-independent module-relative path. By default, this path is relative to the calling module's directory; but if the *package*argument is specified, then it is relative to that package. To ensure OS-independence, each filename should use `/` characters to separate path segments, and may not be an absolute path (i.e., it may not begin with `/`).
- If *module\_relative* is `False`, then each filename in *paths* specifies an OS-specific path. The path may be absolute or relative; relative paths are resolved with respect to the current working directory.
Optional argument *package* is a Python package or the name of a Python package whose directory should be used as the base directory for module-relative filenames in *paths*. If no package is specified, then the calling module's directory is used as the base directory for module-relative filenames. It is an error to specify *package* if *module\_relative* is `False`.
Optional argument *setUp* specifies a set-up function for the test suite. This is called before running the tests in each file. The *setUp* function will be passed a [`DocTest`](#doctest.DocTest "doctest.DocTest") object. The setUp function can access the test globals as the *globs* attribute of the test passed.
Optional argument *tearDown* specifies a tear-down function for the test suite. This is called after running the tests in each file. The *tearDown*function will be passed a [`DocTest`](#doctest.DocTest "doctest.DocTest") object. The setUp function can access the test globals as the *globs* attribute of the test passed.
Optional argument *globs* is a dictionary containing the initial global variables for the tests. A new copy of this dictionary is created for each test. By default, *globs* is a new empty dictionary.
Optional argument *optionflags* specifies the default doctest options for the tests, created by or-ing together individual option flags. See section [Option Flags](#doctest-options). See function [`set_unittest_reportflags()`](#doctest.set_unittest_reportflags "doctest.set_unittest_reportflags") below for a better way to set reporting options.
Optional argument *parser* specifies a [`DocTestParser`](#doctest.DocTestParser "doctest.DocTestParser") (or subclass) that should be used to extract tests from the files. It defaults to a normal parser (i.e., `DocTestParser()`).
Optional argument *encoding* specifies an encoding that should be used to convert the file to unicode.
The global `__file__` is added to the globals provided to doctests loaded from a text file using [`DocFileSuite()`](#doctest.DocFileSuite "doctest.DocFileSuite").
`doctest.``DocTestSuite`(*module=None*, *globs=None*, *extraglobs=None*, *test\_finder=None*, *setUp=None*, *tearDown=None*, *checker=None*)Convert doctest tests for a module to a [`unittest.TestSuite`](unittest.xhtml#unittest.TestSuite "unittest.TestSuite").
The returned [`unittest.TestSuite`](unittest.xhtml#unittest.TestSuite "unittest.TestSuite") is to be run by the unittest framework and runs each doctest in the module. If any of the doctests fail, then the synthesized unit test fails, and a `failureException` exception is raised showing the name of the file containing the test and a (sometimes approximate) line number.
Optional argument *module* provides the module to be tested. It can be a module object or a (possibly dotted) module name. If not specified, the module calling this function is used.
Optional argument *globs* is a dictionary containing the initial global variables for the tests. A new copy of this dictionary is created for each test. By default, *globs* is a new empty dictionary.
Optional argument *extraglobs* specifies an extra set of global variables, which is merged into *globs*. By default, no extra globals are used.
Optional argument *test\_finder* is the [`DocTestFinder`](#doctest.DocTestFinder "doctest.DocTestFinder") object (or a drop-in replacement) that is used to extract doctests from the module.
Optional arguments *setUp*, *tearDown*, and *optionflags* are the same as for function [`DocFileSuite()`](#doctest.DocFileSuite "doctest.DocFileSuite") above.
This function uses the same search technique as [`testmod()`](#doctest.testmod "doctest.testmod").
在 3.5 版更改: [`DocTestSuite()`](#doctest.DocTestSuite "doctest.DocTestSuite") returns an empty [`unittest.TestSuite`](unittest.xhtml#unittest.TestSuite "unittest.TestSuite") if *module*contains no docstrings instead of raising [`ValueError`](exceptions.xhtml#ValueError "ValueError").
Under the covers, [`DocTestSuite()`](#doctest.DocTestSuite "doctest.DocTestSuite") creates a [`unittest.TestSuite`](unittest.xhtml#unittest.TestSuite "unittest.TestSuite") out of `doctest.DocTestCase` instances, and `DocTestCase` is a subclass of [`unittest.TestCase`](unittest.xhtml#unittest.TestCase "unittest.TestCase"). `DocTestCase` isn't documented here (it's an internal detail), but studying its code can answer questions about the exact details of [`unittest`](unittest.xhtml#module-unittest "unittest: Unit testing framework for Python.") integration.
Similarly, [`DocFileSuite()`](#doctest.DocFileSuite "doctest.DocFileSuite") creates a [`unittest.TestSuite`](unittest.xhtml#unittest.TestSuite "unittest.TestSuite") out of `doctest.DocFileCase` instances, and `DocFileCase` is a subclass of `DocTestCase`.
So both ways of creating a [`unittest.TestSuite`](unittest.xhtml#unittest.TestSuite "unittest.TestSuite") run instances of `DocTestCase`. This is important for a subtle reason: when you run [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.") functions yourself, you can control the [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.") options in use directly, by passing option flags to [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.") functions. However, if you're writing a [`unittest`](unittest.xhtml#module-unittest "unittest: Unit testing framework for Python.") framework, [`unittest`](unittest.xhtml#module-unittest "unittest: Unit testing framework for Python.") ultimately controls when and how tests get run. The framework author typically wants to control [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.") reporting options (perhaps, e.g., specified by command line options), but there's no way to pass options through [`unittest`](unittest.xhtml#module-unittest "unittest: Unit testing framework for Python.") to [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.") test runners.
For this reason, [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.") also supports a notion of [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.")reporting flags specific to [`unittest`](unittest.xhtml#module-unittest "unittest: Unit testing framework for Python.") support, via this function:
`doctest.``set_unittest_reportflags`(*flags*)Set the [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.") reporting flags to use.
Argument *flags* takes the [bitwise OR](../reference/expressions.xhtml#bitwise) of option flags. See section [Option Flags](#doctest-options). Only "reporting flags" can be used.
This is a module-global setting, and affects all future doctests run by module [`unittest`](unittest.xhtml#module-unittest "unittest: Unit testing framework for Python."): the `runTest()` method of `DocTestCase` looks at the option flags specified for the test case when the `DocTestCase`instance was constructed. If no reporting flags were specified (which is the typical and expected case), [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.")'s [`unittest`](unittest.xhtml#module-unittest "unittest: Unit testing framework for Python.") reporting flags are [bitwise ORed](../reference/expressions.xhtml#bitwise) into the option flags, and the option flags so augmented are passed to the [`DocTestRunner`](#doctest.DocTestRunner "doctest.DocTestRunner") instance created to run the doctest. If any reporting flags were specified when the `DocTestCase` instance was constructed, [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.")'s [`unittest`](unittest.xhtml#module-unittest "unittest: Unit testing framework for Python.") reporting flags are ignored.
The value of the [`unittest`](unittest.xhtml#module-unittest "unittest: Unit testing framework for Python.") reporting flags in effect before the function was called is returned by the function.
## Advanced API
The basic API is a simple wrapper that's intended to make doctest easy to use. It is fairly flexible, and should meet most users' needs; however, if you require more fine-grained control over testing, or wish to extend doctest's capabilities, then you should use the advanced API.
The advanced API revolves around two container classes, which are used to store the interactive examples extracted from doctest cases:
- [`Example`](#doctest.Example "doctest.Example"): A single Python [statement](../glossary.xhtml#term-statement), paired with its expected output.
- [`DocTest`](#doctest.DocTest "doctest.DocTest"): A collection of [`Example`](#doctest.Example "doctest.Example")s, typically extracted from a single docstring or text file.
Additional processing classes are defined to find, parse, and run, and check doctest examples:
- [`DocTestFinder`](#doctest.DocTestFinder "doctest.DocTestFinder"): Finds all docstrings in a given module, and uses a [`DocTestParser`](#doctest.DocTestParser "doctest.DocTestParser") to create a [`DocTest`](#doctest.DocTest "doctest.DocTest") from every docstring that contains interactive examples.
- [`DocTestParser`](#doctest.DocTestParser "doctest.DocTestParser"): Creates a [`DocTest`](#doctest.DocTest "doctest.DocTest") object from a string (such as an object's docstring).
- [`DocTestRunner`](#doctest.DocTestRunner "doctest.DocTestRunner"): Executes the examples in a [`DocTest`](#doctest.DocTest "doctest.DocTest"), and uses an [`OutputChecker`](#doctest.OutputChecker "doctest.OutputChecker") to verify their output.
- [`OutputChecker`](#doctest.OutputChecker "doctest.OutputChecker"): Compares the actual output from a doctest example with the expected output, and decides whether they match.
The relationships among these processing classes are summarized in the following diagram:
```
list of:
+------+ +---------+
|module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
+------+ | ^ +---------+ | ^ (printed)
| | | Example | | |
v | | ... | v |
DocTestParser | Example | OutputChecker
+---------+
```
### DocTest Objects
*class* `doctest.``DocTest`(*examples*, *globs*, *name*, *filename*, *lineno*, *docstring*)A collection of doctest examples that should be run in a single namespace. The constructor arguments are used to initialize the attributes of the same names.
[`DocTest`](#doctest.DocTest "doctest.DocTest") defines the following attributes. They are initialized by the constructor, and should not be modified directly.
`examples`A list of [`Example`](#doctest.Example "doctest.Example") objects encoding the individual interactive Python examples that should be run by this test.
`globs`The namespace (aka globals) that the examples should be run in. This is a dictionary mapping names to values. Any changes to the namespace made by the examples (such as binding new variables) will be reflected in [`globs`](#doctest.DocTest.globs "doctest.DocTest.globs")after the test is run.
`name`A string name identifying the [`DocTest`](#doctest.DocTest "doctest.DocTest"). Typically, this is the name of the object or file that the test was extracted from.
`filename`The name of the file that this [`DocTest`](#doctest.DocTest "doctest.DocTest") was extracted from; or `None` if the filename is unknown, or if the [`DocTest`](#doctest.DocTest "doctest.DocTest") was not extracted from a file.
`lineno`The line number within [`filename`](#doctest.DocTest.filename "doctest.DocTest.filename") where this [`DocTest`](#doctest.DocTest "doctest.DocTest") begins, or `None` if the line number is unavailable. This line number is zero-based with respect to the beginning of the file.
`docstring`The string that the test was extracted from, or `None` if the string is unavailable, or if the test was not extracted from a string.
### Example Objects
*class* `doctest.``Example`(*source*, *want*, *exc\_msg=None*, *lineno=0*, *indent=0*, *options=None*)A single interactive example, consisting of a Python statement and its expected output. The constructor arguments are used to initialize the attributes of the same names.
[`Example`](#doctest.Example "doctest.Example") defines the following attributes. They are initialized by the constructor, and should not be modified directly.
`source`A string containing the example's source code. This source code consists of a single Python statement, and always ends with a newline; the constructor adds a newline when necessary.
`want`The expected output from running the example's source code (either from stdout, or a traceback in case of exception). [`want`](#doctest.Example.want "doctest.Example.want") ends with a newline unless no output is expected, in which case it's an empty string. The constructor adds a newline when necessary.
`exc_msg`The exception message generated by the example, if the example is expected to generate an exception; or `None` if it is not expected to generate an exception. This exception message is compared against the return value of [`traceback.format_exception_only()`](traceback.xhtml#traceback.format_exception_only "traceback.format_exception_only"). [`exc_msg`](#doctest.Example.exc_msg "doctest.Example.exc_msg") ends with a newline unless it's `None`. The constructor adds a newline if needed.
`lineno`The line number within the string containing this example where the example begins. This line number is zero-based with respect to the beginning of the containing string.
`indent`The example's indentation in the containing string, i.e., the number of space characters that precede the example's first prompt.
`options`A dictionary mapping from option flags to `True` or `False`, which is used to override default options for this example. Any option flags not contained in this dictionary are left at their default value (as specified by the [`DocTestRunner`](#doctest.DocTestRunner "doctest.DocTestRunner")'s `optionflags`). By default, no options are set.
### DocTestFinder objects
*class* `doctest.``DocTestFinder`(*verbose=False*, *parser=DocTestParser()*, *recurse=True*, *exclude\_empty=True*)A processing class used to extract the [`DocTest`](#doctest.DocTest "doctest.DocTest")s that are relevant to a given object, from its docstring and the docstrings of its contained objects. [`DocTest`](#doctest.DocTest "doctest.DocTest")s can be extracted from modules, classes, functions, methods, staticmethods, classmethods, and properties.
The optional argument *verbose* can be used to display the objects searched by the finder. It defaults to `False` (no output).
The optional argument *parser* specifies the [`DocTestParser`](#doctest.DocTestParser "doctest.DocTestParser") object (or a drop-in replacement) that is used to extract doctests from docstrings.
If the optional argument *recurse* is false, then [`DocTestFinder.find()`](#doctest.DocTestFinder.find "doctest.DocTestFinder.find")will only examine the given object, and not any contained objects.
If the optional argument *exclude\_empty* is false, then [`DocTestFinder.find()`](#doctest.DocTestFinder.find "doctest.DocTestFinder.find") will include tests for objects with empty docstrings.
[`DocTestFinder`](#doctest.DocTestFinder "doctest.DocTestFinder") defines the following method:
`find`(*obj\[, name\]\[, module\]\[, globs\]\[, extraglobs\]*)Return a list of the [`DocTest`](#doctest.DocTest "doctest.DocTest")s that are defined by *obj*'s docstring, or by any of its contained objects' docstrings.
The optional argument *name* specifies the object's name; this name will be used to construct names for the returned [`DocTest`](#doctest.DocTest "doctest.DocTest")s. If *name* is not specified, then `obj.__name__` is used.
The optional parameter *module* is the module that contains the given object. If the module is not specified or is `None`, then the test finder will attempt to automatically determine the correct module. The object's module is used:
- As a default namespace, if *globs* is not specified.
- To prevent the DocTestFinder from extracting DocTests from objects that are imported from other modules. (Contained objects with modules other than *module* are ignored.)
- To find the name of the file containing the object.
- To help find the line number of the object within its file.
If *module* is `False`, no attempt to find the module will be made. This is obscure, of use mostly in testing doctest itself: if *module* is `False`, or is `None` but cannot be found automatically, then all objects are considered to belong to the (non-existent) module, so all contained objects will (recursively) be searched for doctests.
The globals for each [`DocTest`](#doctest.DocTest "doctest.DocTest") is formed by combining *globs* and *extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new shallow copy of the globals dictionary is created for each [`DocTest`](#doctest.DocTest "doctest.DocTest"). If *globs* is not specified, then it defaults to the module's *\_\_dict\_\_*, if specified, or `{}` otherwise. If *extraglobs* is not specified, then it defaults to `{}`.
### DocTestParser objects
*class* `doctest.``DocTestParser`A processing class used to extract interactive examples from a string, and use them to create a [`DocTest`](#doctest.DocTest "doctest.DocTest") object.
[`DocTestParser`](#doctest.DocTestParser "doctest.DocTestParser") defines the following methods:
`get_doctest`(*string*, *globs*, *name*, *filename*, *lineno*)Extract all doctest examples from the given string, and collect them into a [`DocTest`](#doctest.DocTest "doctest.DocTest") object.
*globs*, *name*, *filename*, and *lineno* are attributes for the new [`DocTest`](#doctest.DocTest "doctest.DocTest") object. See the documentation for [`DocTest`](#doctest.DocTest "doctest.DocTest") for more information.
`get_examples`(*string*, *name='<string>'*)Extract all doctest examples from the given string, and return them as a list of [`Example`](#doctest.Example "doctest.Example") objects. Line numbers are 0-based. The optional argument *name* is a name identifying this string, and is only used for error messages.
`parse`(*string*, *name='<string>'*)Divide the given string into examples and intervening text, and return them as a list of alternating [`Example`](#doctest.Example "doctest.Example")s and strings. Line numbers for the [`Example`](#doctest.Example "doctest.Example")s are 0-based. The optional argument *name* is a name identifying this string, and is only used for error messages.
### DocTestRunner objects
*class* `doctest.``DocTestRunner`(*checker=None*, *verbose=None*, *optionflags=0*)A processing class used to execute and verify the interactive examples in a [`DocTest`](#doctest.DocTest "doctest.DocTest").
The comparison between expected outputs and actual outputs is done by an [`OutputChecker`](#doctest.OutputChecker "doctest.OutputChecker"). This comparison may be customized with a number of option flags; see section [Option Flags](#doctest-options) for more information. If the option flags are insufficient, then the comparison may also be customized by passing a subclass of [`OutputChecker`](#doctest.OutputChecker "doctest.OutputChecker") to the constructor.
The test runner's display output can be controlled in two ways. First, an output function can be passed to `TestRunner.run()`; this function will be called with strings that should be displayed. It defaults to `sys.stdout.write`. If capturing the output is not sufficient, then the display output can be also customized by subclassing DocTestRunner, and overriding the methods [`report_start()`](#doctest.DocTestRunner.report_start "doctest.DocTestRunner.report_start"), [`report_success()`](#doctest.DocTestRunner.report_success "doctest.DocTestRunner.report_success"), [`report_unexpected_exception()`](#doctest.DocTestRunner.report_unexpected_exception "doctest.DocTestRunner.report_unexpected_exception"), and [`report_failure()`](#doctest.DocTestRunner.report_failure "doctest.DocTestRunner.report_failure").
The optional keyword argument *checker* specifies the [`OutputChecker`](#doctest.OutputChecker "doctest.OutputChecker")object (or drop-in replacement) that should be used to compare the expected outputs to the actual outputs of doctest examples.
The optional keyword argument *verbose* controls the [`DocTestRunner`](#doctest.DocTestRunner "doctest.DocTestRunner")'s verbosity. If *verbose* is `True`, then information is printed about each example, as it is run. If *verbose* is `False`, then only failures are printed. If *verbose* is unspecified, or `None`, then verbose output is used iff the command-line switch `-v` is used.
The optional keyword argument *optionflags* can be used to control how the test runner compares expected output to actual output, and how it displays failures. For more information, see section [Option Flags](#doctest-options).
[`DocTestParser`](#doctest.DocTestParser "doctest.DocTestParser") defines the following methods:
`report_start`(*out*, *test*, *example*)Report that the test runner is about to process the given example. This method is provided to allow subclasses of [`DocTestRunner`](#doctest.DocTestRunner "doctest.DocTestRunner") to customize their output; it should not be called directly.
*example* is the example about to be processed. *test* is the test *containing example*. *out* is the output function that was passed to [`DocTestRunner.run()`](#doctest.DocTestRunner.run "doctest.DocTestRunner.run").
`report_success`(*out*, *test*, *example*, *got*)Report that the given example ran successfully. This method is provided to allow subclasses of [`DocTestRunner`](#doctest.DocTestRunner "doctest.DocTestRunner") to customize their output; it should not be called directly.
*example* is the example about to be processed. *got* is the actual output from the example. *test* is the test containing *example*. *out* is the output function that was passed to [`DocTestRunner.run()`](#doctest.DocTestRunner.run "doctest.DocTestRunner.run").
`report_failure`(*out*, *test*, *example*, *got*)Report that the given example failed. This method is provided to allow subclasses of [`DocTestRunner`](#doctest.DocTestRunner "doctest.DocTestRunner") to customize their output; it should not be called directly.
*example* is the example about to be processed. *got* is the actual output from the example. *test* is the test containing *example*. *out* is the output function that was passed to [`DocTestRunner.run()`](#doctest.DocTestRunner.run "doctest.DocTestRunner.run").
`report_unexpected_exception`(*out*, *test*, *example*, *exc\_info*)Report that the given example raised an unexpected exception. This method is provided to allow subclasses of [`DocTestRunner`](#doctest.DocTestRunner "doctest.DocTestRunner") to customize their output; it should not be called directly.
*example* is the example about to be processed. *exc\_info* is a tuple containing information about the unexpected exception (as returned by [`sys.exc_info()`](sys.xhtml#sys.exc_info "sys.exc_info")). *test* is the test containing *example*. *out* is the output function that was passed to [`DocTestRunner.run()`](#doctest.DocTestRunner.run "doctest.DocTestRunner.run").
`run`(*test*, *compileflags=None*, *out=None*, *clear\_globs=True*)Run the examples in *test* (a [`DocTest`](#doctest.DocTest "doctest.DocTest") object), and display the results using the writer function *out*.
The examples are run in the namespace `test.globs`. If *clear\_globs* is true (the default), then this namespace will be cleared after the test runs, to help with garbage collection. If you would like to examine the namespace after the test completes, then use *clear\_globs=False*.
*compileflags* gives the set of flags that should be used by the Python compiler when running the examples. If not specified, then it will default to the set of future-import flags that apply to *globs*.
The output of each example is checked using the [`DocTestRunner`](#doctest.DocTestRunner "doctest.DocTestRunner")'s output checker, and the results are formatted by the `DocTestRunner.report_*()` methods.
`summarize`(*verbose=None*)Print a summary of all the test cases that have been run by this DocTestRunner, and return a [named tuple](../glossary.xhtml#term-named-tuple)`TestResults(failed, attempted)`.
The optional *verbose* argument controls how detailed the summary is. If the verbosity is not specified, then the [`DocTestRunner`](#doctest.DocTestRunner "doctest.DocTestRunner")'s verbosity is used.
### OutputChecker objects
*class* `doctest.``OutputChecker`A class used to check the whether the actual output from a doctest example matches the expected output. [`OutputChecker`](#doctest.OutputChecker "doctest.OutputChecker") defines two methods: [`check_output()`](#doctest.OutputChecker.check_output "doctest.OutputChecker.check_output"), which compares a given pair of outputs, and returns true if they match; and [`output_difference()`](#doctest.OutputChecker.output_difference "doctest.OutputChecker.output_difference"), which returns a string describing the differences between two outputs.
[`OutputChecker`](#doctest.OutputChecker "doctest.OutputChecker") defines the following methods:
`check_output`(*want*, *got*, *optionflags*)Return `True` iff the actual output from an example (*got*) matches the expected output (*want*). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See section [Option Flags](#doctest-options) for more information about option flags.
`output_difference`(*example*, *got*, *optionflags*)Return a string describing the differences between the expected output for a given example (*example*) and the actual output (*got*). *optionflags* is the set of option flags used to compare *want* and *got*.
## 调试
Doctest provides several mechanisms for debugging doctest examples:
- Several functions convert doctests to executable Python programs, which can be run under the Python debugger, [`pdb`](pdb.xhtml#module-pdb "pdb: The Python debugger for interactive interpreters.").
- The [`DebugRunner`](#doctest.DebugRunner "doctest.DebugRunner") class is a subclass of [`DocTestRunner`](#doctest.DocTestRunner "doctest.DocTestRunner") that raises an exception for the first failing example, containing information about that example. This information can be used to perform post-mortem debugging on the example.
- The [`unittest`](unittest.xhtml#module-unittest "unittest: Unit testing framework for Python.") cases generated by [`DocTestSuite()`](#doctest.DocTestSuite "doctest.DocTestSuite") support the [`debug()`](#doctest.debug "doctest.debug") method defined by [`unittest.TestCase`](unittest.xhtml#unittest.TestCase "unittest.TestCase").
- You can add a call to [`pdb.set_trace()`](pdb.xhtml#pdb.set_trace "pdb.set_trace") in a doctest example, and you'll drop into the Python debugger when that line is executed. Then you can inspect current values of variables, and so on. For example, suppose `a.py`contains just this module docstring:
```
"""
>>> def f(x):
... g(x*2)
>>> def g(x):
... print(x+3)
... import pdb; pdb.set_trace()
>>> f(3)
9
"""
```
Then an interactive Python session may look like this:
```
>>> import a, doctest
>>> doctest.testmod(a)
--Return--
> <doctest a[1]>(3)g()->None
-> import pdb; pdb.set_trace()
(Pdb) list
1 def g(x):
2 print(x+3)
3 -> import pdb; pdb.set_trace()
[EOF]
(Pdb) p x
6
(Pdb) step
--Return--
> <doctest a[0]>(2)f()->None
-> g(x*2)
(Pdb) list
1 def f(x):
2 -> g(x*2)
[EOF]
(Pdb) p x
3
(Pdb) step
--Return--
> <doctest a[2]>(1)?()->None
-> f(3)
(Pdb) cont
(0, 3)
>>>
```
Functions that convert doctests to Python code, and possibly run the synthesized code under the debugger:
`doctest.``script_from_examples`(*s*)Convert text with examples to a script.
Argument *s* is a string containing doctest examples. The string is converted to a Python script, where doctest examples in *s* are converted to regular code, and everything else is converted to Python comments. The generated script is returned as a string. For example,
```
import doctest
print(doctest.script_from_examples(r"""
Set x and y to 1 and 2.
>>> x, y = 1, 2
Print their sum:
>>> print(x+y)
3
"""))
```
displays:
```
# Set x and y to 1 and 2.
x, y = 1, 2
#
# Print their sum:
print(x+y)
# Expected:
## 3
```
This function is used internally by other functions (see below), but can also be useful when you want to transform an interactive Python session into a Python script.
`doctest.``testsource`(*module*, *name*)Convert the doctest for an object to a script.
Argument *module* is a module object, or dotted name of a module, containing the object whose doctests are of interest. Argument *name* is the name (within the module) of the object with the doctests of interest. The result is a string, containing the object's docstring converted to a Python script, as described for [`script_from_examples()`](#doctest.script_from_examples "doctest.script_from_examples") above. For example, if module `a.py`contains a top-level function `f()`, then
```
import a, doctest
print(doctest.testsource(a, "a.f"))
```
prints a script version of function `f()`'s docstring, with doctests converted to code, and the rest placed in comments.
`doctest.``debug`(*module*, *name*, *pm=False*)Debug the doctests for an object.
The *module* and *name* arguments are the same as for function [`testsource()`](#doctest.testsource "doctest.testsource") above. The synthesized Python script for the named object's docstring is written to a temporary file, and then that file is run under the control of the Python debugger, [`pdb`](pdb.xhtml#module-pdb "pdb: The Python debugger for interactive interpreters.").
A shallow copy of `module.__dict__` is used for both local and global execution context.
Optional argument *pm* controls whether post-mortem debugging is used. If *pm*has a true value, the script file is run directly, and the debugger gets involved only if the script terminates via raising an unhandled exception. If it does, then post-mortem debugging is invoked, via [`pdb.post_mortem()`](pdb.xhtml#pdb.post_mortem "pdb.post_mortem"), passing the traceback object from the unhandled exception. If *pm* is not specified, or is false, the script is run under the debugger from the start, via passing an appropriate [`exec()`](functions.xhtml#exec "exec") call to [`pdb.run()`](pdb.xhtml#pdb.run "pdb.run").
`doctest.``debug_src`(*src*, *pm=False*, *globs=None*)Debug the doctests in a string.
This is like function [`debug()`](#doctest.debug "doctest.debug") above, except that a string containing doctest examples is specified directly, via the *src* argument.
Optional argument *pm* has the same meaning as in function [`debug()`](#doctest.debug "doctest.debug") above.
Optional argument *globs* gives a dictionary to use as both local and global execution context. If not specified, or `None`, an empty dictionary is used. If specified, a shallow copy of the dictionary is used.
The [`DebugRunner`](#doctest.DebugRunner "doctest.DebugRunner") class, and the special exceptions it may raise, are of most interest to testing framework authors, and will only be sketched here. See the source code, and especially [`DebugRunner`](#doctest.DebugRunner "doctest.DebugRunner")'s docstring (which is a doctest!) for more details:
*class* `doctest.``DebugRunner`(*checker=None*, *verbose=None*, *optionflags=0*)A subclass of [`DocTestRunner`](#doctest.DocTestRunner "doctest.DocTestRunner") that raises an exception as soon as a failure is encountered. If an unexpected exception occurs, an [`UnexpectedException`](#doctest.UnexpectedException "doctest.UnexpectedException") exception is raised, containing the test, the example, and the original exception. If the output doesn't match, then a [`DocTestFailure`](#doctest.DocTestFailure "doctest.DocTestFailure") exception is raised, containing the test, the example, and the actual output.
For information about the constructor parameters and methods, see the documentation for [`DocTestRunner`](#doctest.DocTestRunner "doctest.DocTestRunner") in section [Advanced API](#doctest-advanced-api).
There are two exceptions that may be raised by [`DebugRunner`](#doctest.DebugRunner "doctest.DebugRunner") instances:
*exception* `doctest.``DocTestFailure`(*test*, *example*, *got*)An exception raised by [`DocTestRunner`](#doctest.DocTestRunner "doctest.DocTestRunner") to signal that a doctest example's actual output did not match its expected output. The constructor arguments are used to initialize the attributes of the same names.
[`DocTestFailure`](#doctest.DocTestFailure "doctest.DocTestFailure") defines the following attributes:
`DocTestFailure.``test`The [`DocTest`](#doctest.DocTest "doctest.DocTest") object that was being run when the example failed.
`DocTestFailure.``example`The [`Example`](#doctest.Example "doctest.Example") that failed.
`DocTestFailure.``got`The example's actual output.
*exception* `doctest.``UnexpectedException`(*test*, *example*, *exc\_info*)An exception raised by [`DocTestRunner`](#doctest.DocTestRunner "doctest.DocTestRunner") to signal that a doctest example raised an unexpected exception. The constructor arguments are used to initialize the attributes of the same names.
[`UnexpectedException`](#doctest.UnexpectedException "doctest.UnexpectedException") defines the following attributes:
`UnexpectedException.``test`The [`DocTest`](#doctest.DocTest "doctest.DocTest") object that was being run when the example failed.
`UnexpectedException.``example`The [`Example`](#doctest.Example "doctest.Example") that failed.
`UnexpectedException.``exc_info`A tuple containing information about the unexpected exception, as returned by [`sys.exc_info()`](sys.xhtml#sys.exc_info "sys.exc_info").
## Soapbox
As mentioned in the introduction, [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.") has grown to have three primary uses:
1. Checking examples in docstrings.
2. Regression testing.
3. Executable documentation / literate testing.
These uses have different requirements, and it is important to distinguish them. In particular, filling your docstrings with obscure test cases makes for bad documentation.
When writing a docstring, choose docstring examples with care. There's an art to this that needs to be learned---it may not be natural at first. Examples should add genuine value to the documentation. A good example can often be worth many words. If done with care, the examples will be invaluable for your users, and will pay back the time it takes to collect them many times over as the years go by and things change. I'm still amazed at how often one of my [`doctest`](#module-doctest "doctest: Test pieces of code within docstrings.")examples stops working after a "harmless" change.
Doctest also makes an excellent tool for regression testing, especially if you don't skimp on explanatory text. By interleaving prose and examples, it becomes much easier to keep track of what's actually being tested, and why. When a test fails, good prose can make it much easier to figure out what the problem is, and how it should be fixed. It's true that you could write extensive comments in code-based testing, but few programmers do. Many have found that using doctest approaches instead leads to much clearer tests. Perhaps this is simply because doctest makes writing prose a little easier than writing code, while writing comments in code is a little harder. I think it goes deeper than just that: the natural attitude when writing a doctest-based test is that you want to explain the fine points of your software, and illustrate them with examples. This in turn naturally leads to test files that start with the simplest features, and logically progress to complications and edge cases. A coherent narrative is the result, instead of a collection of isolated functions that test isolated bits of functionality seemingly at random. It's a different attitude, and produces different results, blurring the distinction between testing and explaining.
Regression testing is best confined to dedicated objects or files. There are several options for organizing tests:
- Write text files containing test cases as interactive examples, and test the files using [`testfile()`](#doctest.testfile "doctest.testfile") or [`DocFileSuite()`](#doctest.DocFileSuite "doctest.DocFileSuite"). This is recommended, although is easiest to do for new projects, designed from the start to use doctest.
- Define functions named `_regrtest_topic` that consist of single docstrings, containing test cases for the named topics. These functions can be included in the same file as the module, or separated out into a separate test file.
- Define a `__test__` dictionary mapping from regression test topics to docstrings containing test cases.
When you have placed your tests in a module, the module can itself be the test runner. When a test fails, you can arrange for your test runner to re-run only the failing doctest while you debug the problem. Here is a minimal example of such a test runner:
```
if __name__ == '__main__':
import doctest
flags = doctest.REPORT_NDIFF|doctest.FAIL_FAST
if len(sys.argv) > 1:
name = sys.argv[1]
if name in globals():
obj = globals()[name]
else:
obj = __test__[name]
doctest.run_docstring_examples(obj, globals(), name=name,
optionflags=flags)
else:
fail, total = doctest.testmod(optionflags=flags)
print("{} failures out of {} tests".format(fail, total))
```
脚注
[1](#id1)Examples containing both expected output and an exception are not supported. Trying to guess where one ends and the other begins is too error-prone, and that also makes for a confusing test.
### 导航
- [索引](../genindex.xhtml "总目录")
- [模块](../py-modindex.xhtml "Python 模块索引") |
- [下一页](unittest.xhtml "unittest --- 单元测试框架") |
- [上一页](pydoc.xhtml "pydoc --- Documentation generator and online help system") |
- ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png)
- [Python](https://www.python.org/) »
- zh\_CN 3.7.3 [文档](../index.xhtml) »
- [Python 标准库](index.xhtml) »
- [开发工具](development.xhtml) »
- $('.inline-search').show(0); |
© [版权所有](../copyright.xhtml) 2001-2019, Python Software Foundation.
Python 软件基金会是一个非盈利组织。 [请捐助。](https://www.python.org/psf/donations/)
最后更新于 5月 21, 2019. [发现了问题](../bugs.xhtml)?
使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 创建。
- Python文档内容
- Python 有什么新变化?
- Python 3.7 有什么新变化
- 摘要 - 发布重点
- 新的特性
- 其他语言特性修改
- 新增模块
- 改进的模块
- C API 的改变
- 构建的改变
- 性能优化
- 其他 CPython 实现的改变
- 已弃用的 Python 行为
- 已弃用的 Python 模块、函数和方法
- 已弃用的 C API 函数和类型
- 平台支持的移除
- API 与特性的移除
- 移除的模块
- Windows 专属的改变
- 移植到 Python 3.7
- Python 3.7.1 中的重要变化
- Python 3.7.2 中的重要变化
- Python 3.6 有什么新变化A
- 摘要 - 发布重点
- 新的特性
- 其他语言特性修改
- 新增模块
- 改进的模块
- 性能优化
- Build and C API Changes
- 其他改进
- 弃用
- 移除
- 移植到Python 3.6
- Python 3.6.2 中的重要变化
- Python 3.6.4 中的重要变化
- Python 3.6.5 中的重要变化
- Python 3.6.7 中的重要变化
- Python 3.5 有什么新变化
- 摘要 - 发布重点
- 新的特性
- 其他语言特性修改
- 新增模块
- 改进的模块
- Other module-level changes
- 性能优化
- Build and C API Changes
- 弃用
- 移除
- Porting to Python 3.5
- Notable changes in Python 3.5.4
- What's New In Python 3.4
- 摘要 - 发布重点
- 新的特性
- 新增模块
- 改进的模块
- CPython Implementation Changes
- 弃用
- 移除
- Porting to Python 3.4
- Changed in 3.4.3
- What's New In Python 3.3
- 摘要 - 发布重点
- PEP 405: Virtual Environments
- PEP 420: Implicit Namespace Packages
- PEP 3118: New memoryview implementation and buffer protocol documentation
- PEP 393: Flexible String Representation
- PEP 397: Python Launcher for Windows
- PEP 3151: Reworking the OS and IO exception hierarchy
- PEP 380: Syntax for Delegating to a Subgenerator
- PEP 409: Suppressing exception context
- PEP 414: Explicit Unicode literals
- PEP 3155: Qualified name for classes and functions
- PEP 412: Key-Sharing Dictionary
- PEP 362: Function Signature Object
- PEP 421: Adding sys.implementation
- Using importlib as the Implementation of Import
- 其他语言特性修改
- A Finer-Grained Import Lock
- Builtin functions and types
- 新增模块
- 改进的模块
- 性能优化
- Build and C API Changes
- 弃用
- Porting to Python 3.3
- What's New In Python 3.2
- PEP 384: Defining a Stable ABI
- PEP 389: Argparse Command Line Parsing Module
- PEP 391: Dictionary Based Configuration for Logging
- PEP 3148: The concurrent.futures module
- PEP 3147: PYC Repository Directories
- PEP 3149: ABI Version Tagged .so Files
- PEP 3333: Python Web Server Gateway Interface v1.0.1
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- 多线程
- 性能优化
- Unicode
- Codecs
- 文档
- IDLE
- Code Repository
- Build and C API Changes
- Porting to Python 3.2
- What's New In Python 3.1
- PEP 372: Ordered Dictionaries
- PEP 378: Format Specifier for Thousands Separator
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- 性能优化
- IDLE
- Build and C API Changes
- Porting to Python 3.1
- What's New In Python 3.0
- Common Stumbling Blocks
- Overview Of Syntax Changes
- Changes Already Present In Python 2.6
- Library Changes
- PEP 3101: A New Approach To String Formatting
- Changes To Exceptions
- Miscellaneous Other Changes
- Build and C API Changes
- 性能
- Porting To Python 3.0
- What's New in Python 2.7
- The Future for Python 2.x
- Changes to the Handling of Deprecation Warnings
- Python 3.1 Features
- PEP 372: Adding an Ordered Dictionary to collections
- PEP 378: Format Specifier for Thousands Separator
- PEP 389: The argparse Module for Parsing Command Lines
- PEP 391: Dictionary-Based Configuration For Logging
- PEP 3106: Dictionary Views
- PEP 3137: The memoryview Object
- 其他语言特性修改
- New and Improved Modules
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.7
- New Features Added to Python 2.7 Maintenance Releases
- Acknowledgements
- Python 2.6 有什么新变化
- Python 3.0
- Changes to the Development Process
- PEP 343: The 'with' statement
- PEP 366: Explicit Relative Imports From a Main Module
- PEP 370: Per-user site-packages Directory
- PEP 371: The multiprocessing Package
- PEP 3101: Advanced String Formatting
- PEP 3105: print As a Function
- PEP 3110: Exception-Handling Changes
- PEP 3112: Byte Literals
- PEP 3116: New I/O Library
- PEP 3118: Revised Buffer Protocol
- PEP 3119: Abstract Base Classes
- PEP 3127: Integer Literal Support and Syntax
- PEP 3129: Class Decorators
- PEP 3141: A Type Hierarchy for Numbers
- 其他语言特性修改
- New and Improved Modules
- Deprecations and Removals
- Build and C API Changes
- Porting to Python 2.6
- Acknowledgements
- What's New in Python 2.5
- PEP 308: Conditional Expressions
- PEP 309: Partial Function Application
- PEP 314: Metadata for Python Software Packages v1.1
- PEP 328: Absolute and Relative Imports
- PEP 338: Executing Modules as Scripts
- PEP 341: Unified try/except/finally
- PEP 342: New Generator Features
- PEP 343: The 'with' statement
- PEP 352: Exceptions as New-Style Classes
- PEP 353: Using ssize_t as the index type
- PEP 357: The 'index' method
- 其他语言特性修改
- New, Improved, and Removed Modules
- Build and C API Changes
- Porting to Python 2.5
- Acknowledgements
- What's New in Python 2.4
- PEP 218: Built-In Set Objects
- PEP 237: Unifying Long Integers and Integers
- PEP 289: Generator Expressions
- PEP 292: Simpler String Substitutions
- PEP 318: Decorators for Functions and Methods
- PEP 322: Reverse Iteration
- PEP 324: New subprocess Module
- PEP 327: Decimal Data Type
- PEP 328: Multi-line Imports
- PEP 331: Locale-Independent Float/String Conversions
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- Build and C API Changes
- Porting to Python 2.4
- Acknowledgements
- What's New in Python 2.3
- PEP 218: A Standard Set Datatype
- PEP 255: Simple Generators
- PEP 263: Source Code Encodings
- PEP 273: Importing Modules from ZIP Archives
- PEP 277: Unicode file name support for Windows NT
- PEP 278: Universal Newline Support
- PEP 279: enumerate()
- PEP 282: The logging Package
- PEP 285: A Boolean Type
- PEP 293: Codec Error Handling Callbacks
- PEP 301: Package Index and Metadata for Distutils
- PEP 302: New Import Hooks
- PEP 305: Comma-separated Files
- PEP 307: Pickle Enhancements
- Extended Slices
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- Pymalloc: A Specialized Object Allocator
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.3
- Acknowledgements
- What's New in Python 2.2
- 概述
- PEPs 252 and 253: Type and Class Changes
- PEP 234: Iterators
- PEP 255: Simple Generators
- PEP 237: Unifying Long Integers and Integers
- PEP 238: Changing the Division Operator
- Unicode Changes
- PEP 227: Nested Scopes
- New and Improved Modules
- Interpreter Changes and Fixes
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.1
- 概述
- PEP 227: Nested Scopes
- PEP 236: future Directives
- PEP 207: Rich Comparisons
- PEP 230: Warning Framework
- PEP 229: New Build System
- PEP 205: Weak References
- PEP 232: Function Attributes
- PEP 235: Importing Modules on Case-Insensitive Platforms
- PEP 217: Interactive Display Hook
- PEP 208: New Coercion Model
- PEP 241: Metadata in Python Packages
- New and Improved Modules
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.0
- 概述
- What About Python 1.6?
- New Development Process
- Unicode
- 列表推导式
- Augmented Assignment
- 字符串的方法
- Garbage Collection of Cycles
- Other Core Changes
- Porting to 2.0
- Extending/Embedding Changes
- Distutils: Making Modules Easy to Install
- XML Modules
- Module changes
- New modules
- IDLE Improvements
- Deleted and Deprecated Modules
- Acknowledgements
- 更新日志
- Python 下一版
- Python 3.7.3 最终版
- Python 3.7.3 发布候选版 1
- Python 3.7.2 最终版
- Python 3.7.2 发布候选版 1
- Python 3.7.1 最终版
- Python 3.7.1 RC 2版本
- Python 3.7.1 发布候选版 1
- Python 3.7.0 正式版
- Python 3.7.0 release candidate 1
- Python 3.7.0 beta 5
- Python 3.7.0 beta 4
- Python 3.7.0 beta 3
- Python 3.7.0 beta 2
- Python 3.7.0 beta 1
- Python 3.7.0 alpha 4
- Python 3.7.0 alpha 3
- Python 3.7.0 alpha 2
- Python 3.7.0 alpha 1
- Python 3.6.6 final
- Python 3.6.6 RC 1
- Python 3.6.5 final
- Python 3.6.5 release candidate 1
- Python 3.6.4 final
- Python 3.6.4 release candidate 1
- Python 3.6.3 final
- Python 3.6.3 release candidate 1
- Python 3.6.2 final
- Python 3.6.2 release candidate 2
- Python 3.6.2 release candidate 1
- Python 3.6.1 final
- Python 3.6.1 release candidate 1
- Python 3.6.0 final
- Python 3.6.0 release candidate 2
- Python 3.6.0 release candidate 1
- Python 3.6.0 beta 4
- Python 3.6.0 beta 3
- Python 3.6.0 beta 2
- Python 3.6.0 beta 1
- Python 3.6.0 alpha 4
- Python 3.6.0 alpha 3
- Python 3.6.0 alpha 2
- Python 3.6.0 alpha 1
- Python 3.5.5 final
- Python 3.5.5 release candidate 1
- Python 3.5.4 final
- Python 3.5.4 release candidate 1
- Python 3.5.3 final
- Python 3.5.3 release candidate 1
- Python 3.5.2 final
- Python 3.5.2 release candidate 1
- Python 3.5.1 final
- Python 3.5.1 release candidate 1
- Python 3.5.0 final
- Python 3.5.0 release candidate 4
- Python 3.5.0 release candidate 3
- Python 3.5.0 release candidate 2
- Python 3.5.0 release candidate 1
- Python 3.5.0 beta 4
- Python 3.5.0 beta 3
- Python 3.5.0 beta 2
- Python 3.5.0 beta 1
- Python 3.5.0 alpha 4
- Python 3.5.0 alpha 3
- Python 3.5.0 alpha 2
- Python 3.5.0 alpha 1
- Python 教程
- 课前甜点
- 使用 Python 解释器
- 调用解释器
- 解释器的运行环境
- Python 的非正式介绍
- Python 作为计算器使用
- 走向编程的第一步
- 其他流程控制工具
- if 语句
- for 语句
- range() 函数
- break 和 continue 语句,以及循环中的 else 子句
- pass 语句
- 定义函数
- 函数定义的更多形式
- 小插曲:编码风格
- 数据结构
- 列表的更多特性
- del 语句
- 元组和序列
- 集合
- 字典
- 循环的技巧
- 深入条件控制
- 序列和其它类型的比较
- 模块
- 有关模块的更多信息
- 标准模块
- dir() 函数
- 包
- 输入输出
- 更漂亮的输出格式
- 读写文件
- 错误和异常
- 语法错误
- 异常
- 处理异常
- 抛出异常
- 用户自定义异常
- 定义清理操作
- 预定义的清理操作
- 类
- 名称和对象
- Python 作用域和命名空间
- 初探类
- 补充说明
- 继承
- 私有变量
- 杂项说明
- 迭代器
- 生成器
- 生成器表达式
- 标准库简介
- 操作系统接口
- 文件通配符
- 命令行参数
- 错误输出重定向和程序终止
- 字符串模式匹配
- 数学
- 互联网访问
- 日期和时间
- 数据压缩
- 性能测量
- 质量控制
- 自带电池
- 标准库简介 —— 第二部分
- 格式化输出
- 模板
- 使用二进制数据记录格式
- 多线程
- 日志
- 弱引用
- 用于操作列表的工具
- 十进制浮点运算
- 虚拟环境和包
- 概述
- 创建虚拟环境
- 使用pip管理包
- 接下来?
- 交互式编辑和编辑历史
- Tab 补全和编辑历史
- 默认交互式解释器的替代品
- 浮点算术:争议和限制
- 表示性错误
- 附录
- 交互模式
- 安装和使用 Python
- 命令行与环境
- 命令行
- 环境变量
- 在Unix平台中使用Python
- 获取最新版本的Python
- 构建Python
- 与Python相关的路径和文件
- 杂项
- 编辑器和集成开发环境
- 在Windows上使用 Python
- 完整安装程序
- Microsoft Store包
- nuget.org 安装包
- 可嵌入的包
- 替代捆绑包
- 配置Python
- 适用于Windows的Python启动器
- 查找模块
- 附加模块
- 在Windows上编译Python
- 其他平台
- 在苹果系统上使用 Python
- 获取和安装 MacPython
- IDE
- 安装额外的 Python 包
- Mac 上的图形界面编程
- 在 Mac 上分发 Python 应用程序
- 其他资源
- Python 语言参考
- 概述
- 其他实现
- 标注
- 词法分析
- 行结构
- 其他形符
- 标识符和关键字
- 字面值
- 运算符
- 分隔符
- 数据模型
- 对象、值与类型
- 标准类型层级结构
- 特殊方法名称
- 协程
- 执行模型
- 程序的结构
- 命名与绑定
- 异常
- 导入系统
- importlib
- 包
- 搜索
- 加载
- 基于路径的查找器
- 替换标准导入系统
- Package Relative Imports
- 有关 main 的特殊事项
- 开放问题项
- 参考文献
- 表达式
- 算术转换
- 原子
- 原型
- await 表达式
- 幂运算符
- 一元算术和位运算
- 二元算术运算符
- 移位运算
- 二元位运算
- 比较运算
- 布尔运算
- 条件表达式
- lambda 表达式
- 表达式列表
- 求值顺序
- 运算符优先级
- 简单语句
- 表达式语句
- 赋值语句
- assert 语句
- pass 语句
- del 语句
- return 语句
- yield 语句
- raise 语句
- break 语句
- continue 语句
- import 语句
- global 语句
- nonlocal 语句
- 复合语句
- if 语句
- while 语句
- for 语句
- try 语句
- with 语句
- 函数定义
- 类定义
- 协程
- 最高层级组件
- 完整的 Python 程序
- 文件输入
- 交互式输入
- 表达式输入
- 完整的语法规范
- Python 标准库
- 概述
- 可用性注释
- 内置函数
- 内置常量
- 由 site 模块添加的常量
- 内置类型
- 逻辑值检测
- 布尔运算 — and, or, not
- 比较
- 数字类型 — int, float, complex
- 迭代器类型
- 序列类型 — list, tuple, range
- 文本序列类型 — str
- 二进制序列类型 — bytes, bytearray, memoryview
- 集合类型 — set, frozenset
- 映射类型 — dict
- 上下文管理器类型
- 其他内置类型
- 特殊属性
- 内置异常
- 基类
- 具体异常
- 警告
- 异常层次结构
- 文本处理服务
- string — 常见的字符串操作
- re — 正则表达式操作
- 模块 difflib 是一个计算差异的助手
- textwrap — Text wrapping and filling
- unicodedata — Unicode 数据库
- stringprep — Internet String Preparation
- readline — GNU readline interface
- rlcompleter — GNU readline的完成函数
- 二进制数据服务
- struct — Interpret bytes as packed binary data
- codecs — Codec registry and base classes
- 数据类型
- datetime — 基础日期/时间数据类型
- calendar — General calendar-related functions
- collections — 容器数据类型
- collections.abc — 容器的抽象基类
- heapq — 堆队列算法
- bisect — Array bisection algorithm
- array — Efficient arrays of numeric values
- weakref — 弱引用
- types — Dynamic type creation and names for built-in types
- copy — 浅层 (shallow) 和深层 (deep) 复制操作
- pprint — 数据美化输出
- reprlib — Alternate repr() implementation
- enum — Support for enumerations
- 数字和数学模块
- numbers — 数字的抽象基类
- math — 数学函数
- cmath — Mathematical functions for complex numbers
- decimal — 十进制定点和浮点运算
- fractions — 分数
- random — 生成伪随机数
- statistics — Mathematical statistics functions
- 函数式编程模块
- itertools — 为高效循环而创建迭代器的函数
- functools — 高阶函数和可调用对象上的操作
- operator — 标准运算符替代函数
- 文件和目录访问
- pathlib — 面向对象的文件系统路径
- os.path — 常见路径操作
- fileinput — Iterate over lines from multiple input streams
- stat — Interpreting stat() results
- filecmp — File and Directory Comparisons
- tempfile — Generate temporary files and directories
- glob — Unix style pathname pattern expansion
- fnmatch — Unix filename pattern matching
- linecache — Random access to text lines
- shutil — High-level file operations
- macpath — Mac OS 9 路径操作函数
- 数据持久化
- pickle —— Python 对象序列化
- copyreg — Register pickle support functions
- shelve — Python object persistence
- marshal — Internal Python object serialization
- dbm — Interfaces to Unix “databases”
- sqlite3 — SQLite 数据库 DB-API 2.0 接口模块
- 数据压缩和存档
- zlib — 与 gzip 兼容的压缩
- gzip — 对 gzip 格式的支持
- bz2 — 对 bzip2 压缩算法的支持
- lzma — 用 LZMA 算法压缩
- zipfile — 在 ZIP 归档中工作
- tarfile — Read and write tar archive files
- 文件格式
- csv — CSV 文件读写
- configparser — Configuration file parser
- netrc — netrc file processing
- xdrlib — Encode and decode XDR data
- plistlib — Generate and parse Mac OS X .plist files
- 加密服务
- hashlib — 安全哈希与消息摘要
- hmac — 基于密钥的消息验证
- secrets — Generate secure random numbers for managing secrets
- 通用操作系统服务
- os — 操作系统接口模块
- io — 处理流的核心工具
- time — 时间的访问和转换
- argparse — 命令行选项、参数和子命令解析器
- getopt — C-style parser for command line options
- 模块 logging — Python 的日志记录工具
- logging.config — 日志记录配置
- logging.handlers — Logging handlers
- getpass — 便携式密码输入工具
- curses — 终端字符单元显示的处理
- curses.textpad — Text input widget for curses programs
- curses.ascii — Utilities for ASCII characters
- curses.panel — A panel stack extension for curses
- platform — Access to underlying platform's identifying data
- errno — Standard errno system symbols
- ctypes — Python 的外部函数库
- 并发执行
- threading — 基于线程的并行
- multiprocessing — 基于进程的并行
- concurrent 包
- concurrent.futures — 启动并行任务
- subprocess — 子进程管理
- sched — 事件调度器
- queue — 一个同步的队列类
- _thread — 底层多线程 API
- _dummy_thread — _thread 的替代模块
- dummy_threading — 可直接替代 threading 模块。
- contextvars — Context Variables
- Context Variables
- Manual Context Management
- asyncio support
- 网络和进程间通信
- asyncio — 异步 I/O
- socket — 底层网络接口
- ssl — TLS/SSL wrapper for socket objects
- select — Waiting for I/O completion
- selectors — 高级 I/O 复用库
- asyncore — 异步socket处理器
- asynchat — 异步 socket 指令/响应 处理器
- signal — Set handlers for asynchronous events
- mmap — Memory-mapped file support
- 互联网数据处理
- email — 电子邮件与 MIME 处理包
- json — JSON 编码和解码器
- mailcap — Mailcap file handling
- mailbox — Manipulate mailboxes in various formats
- mimetypes — Map filenames to MIME types
- base64 — Base16, Base32, Base64, Base85 数据编码
- binhex — 对binhex4文件进行编码和解码
- binascii — 二进制和 ASCII 码互转
- quopri — Encode and decode MIME quoted-printable data
- uu — Encode and decode uuencode files
- 结构化标记处理工具
- html — 超文本标记语言支持
- html.parser — 简单的 HTML 和 XHTML 解析器
- html.entities — HTML 一般实体的定义
- XML处理模块
- xml.etree.ElementTree — The ElementTree XML API
- xml.dom — The Document Object Model API
- xml.dom.minidom — Minimal DOM implementation
- xml.dom.pulldom — Support for building partial DOM trees
- xml.sax — Support for SAX2 parsers
- xml.sax.handler — Base classes for SAX handlers
- xml.sax.saxutils — SAX Utilities
- xml.sax.xmlreader — Interface for XML parsers
- xml.parsers.expat — Fast XML parsing using Expat
- 互联网协议和支持
- webbrowser — 方便的Web浏览器控制器
- cgi — Common Gateway Interface support
- cgitb — Traceback manager for CGI scripts
- wsgiref — WSGI Utilities and Reference Implementation
- urllib — URL 处理模块
- urllib.request — 用于打开 URL 的可扩展库
- urllib.response — Response classes used by urllib
- urllib.parse — Parse URLs into components
- urllib.error — Exception classes raised by urllib.request
- urllib.robotparser — Parser for robots.txt
- http — HTTP 模块
- http.client — HTTP协议客户端
- ftplib — FTP protocol client
- poplib — POP3 protocol client
- imaplib — IMAP4 protocol client
- nntplib — NNTP protocol client
- smtplib —SMTP协议客户端
- smtpd — SMTP Server
- telnetlib — Telnet client
- uuid — UUID objects according to RFC 4122
- socketserver — A framework for network servers
- http.server — HTTP 服务器
- http.cookies — HTTP state management
- http.cookiejar — Cookie handling for HTTP clients
- xmlrpc — XMLRPC 服务端与客户端模块
- xmlrpc.client — XML-RPC client access
- xmlrpc.server — Basic XML-RPC servers
- ipaddress — IPv4/IPv6 manipulation library
- 多媒体服务
- audioop — Manipulate raw audio data
- aifc — Read and write AIFF and AIFC files
- sunau — 读写 Sun AU 文件
- wave — 读写WAV格式文件
- chunk — Read IFF chunked data
- colorsys — Conversions between color systems
- imghdr — 推测图像类型
- sndhdr — 推测声音文件的类型
- ossaudiodev — Access to OSS-compatible audio devices
- 国际化
- gettext — 多语种国际化服务
- locale — 国际化服务
- 程序框架
- turtle — 海龟绘图
- cmd — 支持面向行的命令解释器
- shlex — Simple lexical analysis
- Tk图形用户界面(GUI)
- tkinter — Tcl/Tk的Python接口
- tkinter.ttk — Tk themed widgets
- tkinter.tix — Extension widgets for Tk
- tkinter.scrolledtext — 滚动文字控件
- IDLE
- 其他图形用户界面(GUI)包
- 开发工具
- typing — 类型标注支持
- pydoc — Documentation generator and online help system
- doctest — Test interactive Python examples
- unittest — 单元测试框架
- unittest.mock — mock object library
- unittest.mock 上手指南
- 2to3 - 自动将 Python 2 代码转为 Python 3 代码
- test — Regression tests package for Python
- test.support — Utilities for the Python test suite
- test.support.script_helper — Utilities for the Python execution tests
- 调试和分析
- bdb — Debugger framework
- faulthandler — Dump the Python traceback
- pdb — The Python Debugger
- The Python Profilers
- timeit — 测量小代码片段的执行时间
- trace — Trace or track Python statement execution
- tracemalloc — Trace memory allocations
- 软件打包和分发
- distutils — 构建和安装 Python 模块
- ensurepip — Bootstrapping the pip installer
- venv — 创建虚拟环境
- zipapp — Manage executable Python zip archives
- Python运行时服务
- sys — 系统相关的参数和函数
- sysconfig — Provide access to Python's configuration information
- builtins — 内建对象
- main — 顶层脚本环境
- warnings — Warning control
- dataclasses — 数据类
- contextlib — Utilities for with-statement contexts
- abc — 抽象基类
- atexit — 退出处理器
- traceback — Print or retrieve a stack traceback
- future — Future 语句定义
- gc — 垃圾回收器接口
- inspect — 检查对象
- site — Site-specific configuration hook
- 自定义 Python 解释器
- code — Interpreter base classes
- codeop — Compile Python code
- 导入模块
- zipimport — Import modules from Zip archives
- pkgutil — Package extension utility
- modulefinder — 查找脚本使用的模块
- runpy — Locating and executing Python modules
- importlib — The implementation of import
- Python 语言服务
- parser — Access Python parse trees
- ast — 抽象语法树
- symtable — Access to the compiler's symbol tables
- symbol — 与 Python 解析树一起使用的常量
- token — 与Python解析树一起使用的常量
- keyword — 检验Python关键字
- tokenize — Tokenizer for Python source
- tabnanny — 模糊缩进检测
- pyclbr — Python class browser support
- py_compile — Compile Python source files
- compileall — Byte-compile Python libraries
- dis — Python 字节码反汇编器
- pickletools — Tools for pickle developers
- 杂项服务
- formatter — Generic output formatting
- Windows系统相关模块
- msilib — Read and write Microsoft Installer files
- msvcrt — Useful routines from the MS VC++ runtime
- winreg — Windows 注册表访问
- winsound — Sound-playing interface for Windows
- Unix 专有服务
- posix — The most common POSIX system calls
- pwd — 用户密码数据库
- spwd — The shadow password database
- grp — The group database
- crypt — Function to check Unix passwords
- termios — POSIX style tty control
- tty — 终端控制功能
- pty — Pseudo-terminal utilities
- fcntl — The fcntl and ioctl system calls
- pipes — Interface to shell pipelines
- resource — Resource usage information
- nis — Interface to Sun's NIS (Yellow Pages)
- Unix syslog 库例程
- 被取代的模块
- optparse — Parser for command line options
- imp — Access the import internals
- 未创建文档的模块
- 平台特定模块
- 扩展和嵌入 Python 解释器
- 推荐的第三方工具
- 不使用第三方工具创建扩展
- 使用 C 或 C++ 扩展 Python
- 自定义扩展类型:教程
- 定义扩展类型:已分类主题
- 构建C/C++扩展
- 在Windows平台编译C和C++扩展
- 在更大的应用程序中嵌入 CPython 运行时
- Embedding Python in Another Application
- Python/C API 参考手册
- 概述
- 代码标准
- 包含文件
- 有用的宏
- 对象、类型和引用计数
- 异常
- 嵌入Python
- 调试构建
- 稳定的应用程序二进制接口
- The Very High Level Layer
- Reference Counting
- 异常处理
- Printing and clearing
- 抛出异常
- Issuing warnings
- Querying the error indicator
- Signal Handling
- Exception Classes
- Exception Objects
- Unicode Exception Objects
- Recursion Control
- 标准异常
- 标准警告类别
- 工具
- 操作系统实用程序
- 系统功能
- 过程控制
- 导入模块
- Data marshalling support
- 语句解释及变量编译
- 字符串转换与格式化
- 反射
- 编解码器注册与支持功能
- 抽象对象层
- Object Protocol
- 数字协议
- Sequence Protocol
- Mapping Protocol
- 迭代器协议
- 缓冲协议
- Old Buffer Protocol
- 具体的对象层
- 基本对象
- 数值对象
- 序列对象
- 容器对象
- 函数对象
- 其他对象
- Initialization, Finalization, and Threads
- 在Python初始化之前
- 全局配置变量
- Initializing and finalizing the interpreter
- Process-wide parameters
- Thread State and the Global Interpreter Lock
- Sub-interpreter support
- Asynchronous Notifications
- Profiling and Tracing
- Advanced Debugger Support
- Thread Local Storage Support
- 内存管理
- 概述
- 原始内存接口
- Memory Interface
- 对象分配器
- 默认内存分配器
- Customize Memory Allocators
- The pymalloc allocator
- tracemalloc C API
- 示例
- 对象实现支持
- 在堆中分配对象
- Common Object Structures
- Type 对象
- Number Object Structures
- Mapping Object Structures
- Sequence Object Structures
- Buffer Object Structures
- Async Object Structures
- 使对象类型支持循环垃圾回收
- API 和 ABI 版本管理
- 分发 Python 模块
- 关键术语
- 开源许可与协作
- 安装工具
- 阅读指南
- 我该如何...?
- ...为我的项目选择一个名字?
- ...创建和分发二进制扩展?
- 安装 Python 模块
- 关键术语
- 基本使用
- 我应如何 ...?
- ... 在 Python 3.4 之前的 Python 版本中安装 pip ?
- ... 只为当前用户安装软件包?
- ... 安装科学计算类 Python 软件包?
- ... 使用并行安装的多个 Python 版本?
- 常见的安装问题
- 在 Linux 的系统 Python 版本上安装
- 未安装 pip
- 安装二进制编译扩展
- Python 常用指引
- 将 Python 2 代码迁移到 Python 3
- 简要说明
- 详情
- 将扩展模块移植到 Python 3
- 条件编译
- 对象API的更改
- 模块初始化和状态
- CObject 替换为 Capsule
- 其他选项
- Curses Programming with Python
- What is curses?
- Starting and ending a curses application
- Windows and Pads
- Displaying Text
- User Input
- For More Information
- 实现描述器
- 摘要
- 定义和简介
- 描述器协议
- 发起调用描述符
- 描述符示例
- Properties
- 函数和方法
- Static Methods and Class Methods
- 函数式编程指引
- 概述
- 迭代器
- 生成器表达式和列表推导式
- 生成器
- 内置函数
- itertools 模块
- The functools module
- Small functions and the lambda expression
- Revision History and Acknowledgements
- 引用文献
- 日志 HOWTO
- 日志基础教程
- 进阶日志教程
- 日志级别
- 有用的处理程序
- 记录日志中引发的异常
- 使用任意对象作为消息
- 优化
- 日志操作手册
- 在多个模块中使用日志
- 在多线程中使用日志
- 使用多个日志处理器和多种格式化
- 在多个地方记录日志
- 日志服务器配置示例
- 处理日志处理器的阻塞
- Sending and receiving logging events across a network
- Adding contextual information to your logging output
- Logging to a single file from multiple processes
- Using file rotation
- Use of alternative formatting styles
- Customizing LogRecord
- Subclassing QueueHandler - a ZeroMQ example
- Subclassing QueueListener - a ZeroMQ example
- An example dictionary-based configuration
- Using a rotator and namer to customize log rotation processing
- A more elaborate multiprocessing example
- Inserting a BOM into messages sent to a SysLogHandler
- Implementing structured logging
- Customizing handlers with dictConfig()
- Using particular formatting styles throughout your application
- Configuring filters with dictConfig()
- Customized exception formatting
- Speaking logging messages
- Buffering logging messages and outputting them conditionally
- Formatting times using UTC (GMT) via configuration
- Using a context manager for selective logging
- 正则表达式HOWTO
- 概述
- 简单模式
- 使用正则表达式
- 更多模式能力
- 修改字符串
- 常见问题
- 反馈
- 套接字编程指南
- 套接字
- 创建套接字
- 使用一个套接字
- 断开连接
- 非阻塞的套接字
- 排序指南
- 基本排序
- 关键函数
- Operator 模块函数
- 升序和降序
- 排序稳定性和排序复杂度
- 使用装饰-排序-去装饰的旧方法
- 使用 cmp 参数的旧方法
- 其它
- Unicode 指南
- Unicode 概述
- Python's Unicode Support
- Reading and Writing Unicode Data
- Acknowledgements
- 如何使用urllib包获取网络资源
- 概述
- Fetching URLs
- 处理异常
- info and geturl
- Openers and Handlers
- Basic Authentication
- Proxies
- Sockets and Layers
- 脚注
- Argparse 教程
- 概念
- 基础
- 位置参数介绍
- Introducing Optional arguments
- Combining Positional and Optional arguments
- Getting a little more advanced
- Conclusion
- ipaddress模块介绍
- 创建 Address/Network/Interface 对象
- 审查 Address/Network/Interface 对象
- Network 作为 Address 列表
- 比较
- 将IP地址与其他模块一起使用
- 实例创建失败时获取更多详细信息
- Argument Clinic How-To
- The Goals Of Argument Clinic
- Basic Concepts And Usage
- Converting Your First Function
- Advanced Topics
- 使用 DTrace 和 SystemTap 检测CPython
- Enabling the static markers
- Static DTrace probes
- Static SystemTap markers
- Available static markers
- SystemTap Tapsets
- 示例
- Python 常见问题
- Python常见问题
- 一般信息
- 现实世界中的 Python
- 编程常见问题
- 一般问题
- 核心语言
- 数字和字符串
- 性能
- 序列(元组/列表)
- 对象
- 模块
- 设计和历史常见问题
- 为什么Python使用缩进来分组语句?
- 为什么简单的算术运算得到奇怪的结果?
- 为什么浮点计算不准确?
- 为什么Python字符串是不可变的?
- 为什么必须在方法定义和调用中显式使用“self”?
- 为什么不能在表达式中赋值?
- 为什么Python对某些功能(例如list.index())使用方法来实现,而其他功能(例如len(List))使用函数实现?
- 为什么 join()是一个字符串方法而不是列表或元组方法?
- 异常有多快?
- 为什么Python中没有switch或case语句?
- 难道不能在解释器中模拟线程,而非得依赖特定于操作系统的线程实现吗?
- 为什么lambda表达式不能包含语句?
- 可以将Python编译为机器代码,C或其他语言吗?
- Python如何管理内存?
- 为什么CPython不使用更传统的垃圾回收方案?
- CPython退出时为什么不释放所有内存?
- 为什么有单独的元组和列表数据类型?
- 列表是如何在CPython中实现的?
- 字典是如何在CPython中实现的?
- 为什么字典key必须是不可变的?
- 为什么 list.sort() 没有返回排序列表?
- 如何在Python中指定和实施接口规范?
- 为什么没有goto?
- 为什么原始字符串(r-strings)不能以反斜杠结尾?
- 为什么Python没有属性赋值的“with”语句?
- 为什么 if/while/def/class语句需要冒号?
- 为什么Python在列表和元组的末尾允许使用逗号?
- 代码库和插件 FAQ
- 通用的代码库问题
- 通用任务
- 线程相关
- 输入输出
- 网络 / Internet 编程
- 数据库
- 数学和数字
- 扩展/嵌入常见问题
- 可以使用C语言中创建自己的函数吗?
- 可以使用C++语言中创建自己的函数吗?
- C很难写,有没有其他选择?
- 如何从C执行任意Python语句?
- 如何从C中评估任意Python表达式?
- 如何从Python对象中提取C的值?
- 如何使用Py_BuildValue()创建任意长度的元组?
- 如何从C调用对象的方法?
- 如何捕获PyErr_Print()(或打印到stdout / stderr的任何内容)的输出?
- 如何从C访问用Python编写的模块?
- 如何从Python接口到C ++对象?
- 我使用Setup文件添加了一个模块,为什么make失败了?
- 如何调试扩展?
- 我想在Linux系统上编译一个Python模块,但是缺少一些文件。为什么?
- 如何区分“输入不完整”和“输入无效”?
- 如何找到未定义的g++符号__builtin_new或__pure_virtual?
- 能否创建一个对象类,其中部分方法在C中实现,而其他方法在Python中实现(例如通过继承)?
- Python在Windows上的常见问题
- 我怎样在Windows下运行一个Python程序?
- 我怎么让 Python 脚本可执行?
- 为什么有时候 Python 程序会启动缓慢?
- 我怎样使用Python脚本制作可执行文件?
- *.pyd 文件和DLL文件相同吗?
- 我怎样将Python嵌入一个Windows程序?
- 如何让编辑器不要在我的 Python 源代码中插入 tab ?
- 如何在不阻塞的情况下检查按键?
- 图形用户界面(GUI)常见问题
- 图形界面常见问题
- Python 是否有平台无关的图形界面工具包?
- 有哪些Python的GUI工具是某个平台专用的?
- 有关Tkinter的问题
- “为什么我的电脑上安装了 Python ?”
- 什么是Python?
- 为什么我的电脑上安装了 Python ?
- 我能删除 Python 吗?
- 术语对照表
- 文档说明
- Python 文档贡献者
- 解决 Bug
- 文档错误
- 使用 Python 的错误追踪系统
- 开始为 Python 贡献您的知识
- 版权
- 历史和许可证
- 软件历史
- 访问Python或以其他方式使用Python的条款和条件
- Python 3.7.3 的 PSF 许可协议
- Python 2.0 的 BeOpen.com 许可协议
- Python 1.6.1 的 CNRI 许可协议
- Python 0.9.0 至 1.2 的 CWI 许可协议
- 集成软件的许可和认可
- Mersenne Twister
- 套接字
- Asynchronous socket services
- Cookie management
- Execution tracing
- UUencode and UUdecode functions
- XML Remote Procedure Calls
- test_epoll
- Select kqueue
- SipHash24
- strtod and dtoa
- OpenSSL
- expat
- libffi
- zlib
- cfuhash
- libmpdec