### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](unittest.xhtml "unittest --- 單元測試框架") |
- [上一頁](pydoc.xhtml "pydoc --- Documentation generator and online help system") |
- 
- [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") |
- 
- [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