### 导航
- [索引](../genindex.xhtml "总目录")
- [模块](../py-modindex.xhtml "Python 模块索引") |
- [下一页](unittest.mock-examples.xhtml "unittest.mock 上手指南") |
- [上一页](unittest.xhtml "unittest --- 单元测试框架") |
- ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png)
- [Python](https://www.python.org/) »
- zh\_CN 3.7.3 [文档](../index.xhtml) »
- [Python 标准库](index.xhtml) »
- [开发工具](development.xhtml) »
- $('.inline-search').show(0); |
# [`unittest.mock`](#module-unittest.mock "unittest.mock: Mock object library.") --- mock object library
3\.3 新版功能.
**Source code:** [Lib/unittest/mock.py](https://github.com/python/cpython/tree/3.7/Lib/unittest/mock.py) \[https://github.com/python/cpython/tree/3.7/Lib/unittest/mock.py\]
- - - - - -
[`unittest.mock`](#module-unittest.mock "unittest.mock: Mock object library.") is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.
[`unittest.mock`](#module-unittest.mock "unittest.mock: Mock object library.") provides a core [`Mock`](#unittest.mock.Mock "unittest.mock.Mock") class removing the need to create a host of stubs throughout your test suite. After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with. You can also specify return values and set needed attributes in the normal way.
Additionally, mock provides a [`patch()`](#unittest.mock.patch "unittest.mock.patch") decorator that handles patching module and class level attributes within the scope of a test, along with [`sentinel`](#unittest.mock.sentinel "unittest.mock.sentinel") for creating unique objects. See the [quick guide](#quick-guide) for some examples of how to use [`Mock`](#unittest.mock.Mock "unittest.mock.Mock"), [`MagicMock`](#unittest.mock.MagicMock "unittest.mock.MagicMock") and [`patch()`](#unittest.mock.patch "unittest.mock.patch").
Mock is very easy to use and is designed for use with [`unittest`](unittest.xhtml#module-unittest "unittest: Unit testing framework for Python."). Mock is based on the 'action -> assertion' pattern instead of 'record -> replay' used by many mocking frameworks.
There is a backport of [`unittest.mock`](#module-unittest.mock "unittest.mock: Mock object library.") for earlier versions of Python, available as [mock on PyPI](https://pypi.org/project/mock) \[https://pypi.org/project/mock\].
## Quick Guide
[`Mock`](#unittest.mock.Mock "unittest.mock.Mock") and [`MagicMock`](#unittest.mock.MagicMock "unittest.mock.MagicMock") objects create all attributes and methods as you access them and store details of how they have been used. You can configure them, to specify return values or limit what attributes are available, and then make assertions about how they have been used:
```
>>> from unittest.mock import MagicMock
>>> thing = ProductionClass()
>>> thing.method = MagicMock(return_value=3)
>>> thing.method(3, 4, 5, key='value')
3
>>> thing.method.assert_called_with(3, 4, 5, key='value')
```
`side_effect` allows you to perform side effects, including raising an exception when a mock is called:
```
>>> mock = Mock(side_effect=KeyError('foo'))
>>> mock()
Traceback (most recent call last):
...
KeyError: 'foo'
```
```
>>> values = {'a': 1, 'b': 2, 'c': 3}
>>> def side_effect(arg):
... return values[arg]
...
>>> mock.side_effect = side_effect
>>> mock('a'), mock('b'), mock('c')
(1, 2, 3)
>>> mock.side_effect = [5, 4, 3, 2, 1]
>>> mock(), mock(), mock()
(5, 4, 3)
```
Mock has many other ways you can configure it and control its behaviour. For example the *spec* argument configures the mock to take its specification from another object. Attempting to access attributes or methods on the mock that don't exist on the spec will fail with an [`AttributeError`](exceptions.xhtml#AttributeError "AttributeError").
The [`patch()`](#unittest.mock.patch "unittest.mock.patch") decorator / context manager makes it easy to mock classes or objects in a module under test. The object you specify will be replaced with a mock (or other object) during the test and restored when the test ends:
```
>>> from unittest.mock import patch
>>> @patch('module.ClassName2')
... @patch('module.ClassName1')
... def test(MockClass1, MockClass2):
... module.ClassName1()
... module.ClassName2()
... assert MockClass1 is module.ClassName1
... assert MockClass2 is module.ClassName2
... assert MockClass1.called
... assert MockClass2.called
...
>>> test()
```
注解
When you nest patch decorators the mocks are passed in to the decorated function in the same order they applied (the normal *Python* order that decorators are applied). This means from the bottom up, so in the example above the mock for `module.ClassName1` is passed in first.
With [`patch()`](#unittest.mock.patch "unittest.mock.patch") it matters that you patch objects in the namespace where they are looked up. This is normally straightforward, but for a quick guide read [where to patch](#where-to-patch).
As well as a decorator [`patch()`](#unittest.mock.patch "unittest.mock.patch") can be used as a context manager in a with statement:
```
>>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method:
... thing = ProductionClass()
... thing.method(1, 2, 3)
...
>>> mock_method.assert_called_once_with(1, 2, 3)
```
There is also [`patch.dict()`](#unittest.mock.patch.dict "unittest.mock.patch.dict") for setting values in a dictionary just during a scope and restoring the dictionary to its original state when the test ends:
```
>>> foo = {'key': 'value'}
>>> original = foo.copy()
>>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
... assert foo == {'newkey': 'newvalue'}
...
>>> assert foo == original
```
Mock supports the mocking of Python [magic methods](#magic-methods). The easiest way of using magic methods is with the [`MagicMock`](#unittest.mock.MagicMock "unittest.mock.MagicMock") class. It allows you to do things like:
```
>>> mock = MagicMock()
>>> mock.__str__.return_value = 'foobarbaz'
>>> str(mock)
'foobarbaz'
>>> mock.__str__.assert_called_with()
```
Mock allows you to assign functions (or other Mock instances) to magic methods and they will be called appropriately. The [`MagicMock`](#unittest.mock.MagicMock "unittest.mock.MagicMock") class is just a Mock variant that has all of the magic methods pre-created for you (well, all the useful ones anyway).
The following is an example of using magic methods with the ordinary Mock class:
```
>>> mock = Mock()
>>> mock.__str__ = Mock(return_value='wheeeeee')
>>> str(mock)
'wheeeeee'
```
For ensuring that the mock objects in your tests have the same api as the objects they are replacing, you can use [auto-speccing](#auto-speccing). Auto-speccing can be done through the *autospec* argument to patch, or the [`create_autospec()`](#unittest.mock.create_autospec "unittest.mock.create_autospec") function. Auto-speccing creates mock objects that have the same attributes and methods as the objects they are replacing, and any functions and methods (including constructors) have the same call signature as the real object.
This ensures that your mocks will fail in the same way as your production code if they are used incorrectly:
```
>>> from unittest.mock import create_autospec
>>> def function(a, b, c):
... pass
...
>>> mock_function = create_autospec(function, return_value='fishy')
>>> mock_function(1, 2, 3)
'fishy'
>>> mock_function.assert_called_once_with(1, 2, 3)
>>> mock_function('wrong arguments')
Traceback (most recent call last):
...
TypeError: <lambda>() takes exactly 3 arguments (1 given)
```
[`create_autospec()`](#unittest.mock.create_autospec "unittest.mock.create_autospec") can also be used on classes, where it copies the signature of the `__init__` method, and on callable objects where it copies the signature of the `__call__` method.
## The Mock Class
[`Mock`](#unittest.mock.Mock "unittest.mock.Mock") is a flexible mock object intended to replace the use of stubs and test doubles throughout your code. Mocks are callable and create attributes as new mocks when you access them [1](#id3). Accessing the same attribute will always return the same mock. Mocks record how you use them, allowing you to make assertions about what your code has done to them.
[`MagicMock`](#unittest.mock.MagicMock "unittest.mock.MagicMock") is a subclass of [`Mock`](#unittest.mock.Mock "unittest.mock.Mock") with all the magic methods pre-created and ready to use. There are also non-callable variants, useful when you are mocking out objects that aren't callable: [`NonCallableMock`](#unittest.mock.NonCallableMock "unittest.mock.NonCallableMock") and [`NonCallableMagicMock`](#unittest.mock.NonCallableMagicMock "unittest.mock.NonCallableMagicMock")
The [`patch()`](#unittest.mock.patch "unittest.mock.patch") decorators makes it easy to temporarily replace classes in a particular module with a [`Mock`](#unittest.mock.Mock "unittest.mock.Mock") object. By default [`patch()`](#unittest.mock.patch "unittest.mock.patch") will create a [`MagicMock`](#unittest.mock.MagicMock "unittest.mock.MagicMock") for you. You can specify an alternative class of [`Mock`](#unittest.mock.Mock "unittest.mock.Mock") using the *new\_callable* argument to [`patch()`](#unittest.mock.patch "unittest.mock.patch").
*class* `unittest.mock.``Mock`(*spec=None*, *side\_effect=None*, *return\_value=DEFAULT*, *wraps=None*, *name=None*, *spec\_set=None*, *unsafe=False*, *\*\*kwargs*)Create a new [`Mock`](#unittest.mock.Mock "unittest.mock.Mock") object. [`Mock`](#unittest.mock.Mock "unittest.mock.Mock") takes several optional arguments that specify the behaviour of the Mock object:
- *spec*: This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). Accessing any attribute not in this list will raise an [`AttributeError`](exceptions.xhtml#AttributeError "AttributeError").
If *spec* is an object (rather than a list of strings) then [`__class__`](stdtypes.xhtml#instance.__class__ "instance.__class__") returns the class of the spec object. This allows mocks to pass [`isinstance()`](functions.xhtml#isinstance "isinstance") tests.
- *spec\_set*: A stricter variant of *spec*. If used, attempting to *set*or get an attribute on the mock that isn't on the object passed as *spec\_set* will raise an [`AttributeError`](exceptions.xhtml#AttributeError "AttributeError").
- *side\_effect*: A function to be called whenever the Mock is called. See the [`side_effect`](#unittest.mock.Mock.side_effect "unittest.mock.Mock.side_effect") attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns [`DEFAULT`](#unittest.mock.DEFAULT "unittest.mock.DEFAULT"), the return value of this function is used as the return value.
Alternatively *side\_effect* can be an exception class or instance. In this case the exception will be raised when the mock is called.
If *side\_effect* is an iterable then each call to the mock will return the next value from the iterable.
A *side\_effect* can be cleared by setting it to `None`.
- *return\_value*: The value returned when the mock is called. By default this is a new Mock (created on first access). See the [`return_value`](#unittest.mock.Mock.return_value "unittest.mock.Mock.return_value") attribute.
- *unsafe*: By default if any attribute starts with *assert* or *assret* will raise an [`AttributeError`](exceptions.xhtml#AttributeError "AttributeError"). Passing `unsafe=True`will allow access to these attributes.
3\.5 新版功能.
- *wraps*: Item for the mock object to wrap. If *wraps* is not `None` then calling the Mock will pass the call through to the wrapped object (returning the real result). Attribute access on the mock will return a Mock object that wraps the corresponding attribute of the wrapped object (so attempting to access an attribute that doesn't exist will raise an [`AttributeError`](exceptions.xhtml#AttributeError "AttributeError")).
If the mock has an explicit *return\_value* set then calls are not passed to the wrapped object and the *return\_value* is returned instead.
- *name*: If the mock has a name then it will be used in the repr of the mock. This can be useful for debugging. The name is propagated to child mocks.
Mocks can also be called with arbitrary keyword arguments. These will be used to set attributes on the mock after it is created. See the [`configure_mock()`](#unittest.mock.Mock.configure_mock "unittest.mock.Mock.configure_mock") method for details.
`assert_called`(*\*args*, *\*\*kwargs*)Assert that the mock was called at least once.
```
>>> mock = Mock()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called()
```
3\.6 新版功能.
`assert_called_once`(*\*args*, *\*\*kwargs*)Assert that the mock was called exactly once.
```
>>> mock = Mock()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_once()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_once()
Traceback (most recent call last):
...
AssertionError: Expected 'method' to have been called once. Called 2 times.
```
3\.6 新版功能.
`assert_called_with`(*\*args*, *\*\*kwargs*)This method is a convenient way of asserting that calls are made in a particular way:
```
>>> mock = Mock()
>>> mock.method(1, 2, 3, test='wow')
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_with(1, 2, 3, test='wow')
```
`assert_called_once_with`(*\*args*, *\*\*kwargs*)Assert that the mock was called exactly once and that that call was with the specified arguments.
```
>>> mock = Mock(return_value=None)
>>> mock('foo', bar='baz')
>>> mock.assert_called_once_with('foo', bar='baz')
>>> mock('other', bar='values')
>>> mock.assert_called_once_with('other', bar='values')
Traceback (most recent call last):
...
AssertionError: Expected 'mock' to be called once. Called 2 times.
```
`assert_any_call`(*\*args*, *\*\*kwargs*)assert the mock has been called with the specified arguments.
The assert passes if the mock has *ever* been called, unlike [`assert_called_with()`](#unittest.mock.Mock.assert_called_with "unittest.mock.Mock.assert_called_with") and [`assert_called_once_with()`](#unittest.mock.Mock.assert_called_once_with "unittest.mock.Mock.assert_called_once_with") that only pass if the call is the most recent one, and in the case of [`assert_called_once_with()`](#unittest.mock.Mock.assert_called_once_with "unittest.mock.Mock.assert_called_once_with") it must also be the only call.
```
>>> mock = Mock(return_value=None)
>>> mock(1, 2, arg='thing')
>>> mock('some', 'thing', 'else')
>>> mock.assert_any_call(1, 2, arg='thing')
```
`assert_has_calls`(*calls*, *any\_order=False*)assert the mock has been called with the specified calls. The [`mock_calls`](#unittest.mock.Mock.mock_calls "unittest.mock.Mock.mock_calls") list is checked for the calls.
If *any\_order* is false (the default) then the calls must be sequential. There can be extra calls before or after the specified calls.
If *any\_order* is true then the calls can be in any order, but they must all appear in [`mock_calls`](#unittest.mock.Mock.mock_calls "unittest.mock.Mock.mock_calls").
```
>>> mock = Mock(return_value=None)
>>> mock(1)
>>> mock(2)
>>> mock(3)
>>> mock(4)
>>> calls = [call(2), call(3)]
>>> mock.assert_has_calls(calls)
>>> calls = [call(4), call(2), call(3)]
>>> mock.assert_has_calls(calls, any_order=True)
```
`assert_not_called`()Assert the mock was never called.
```
>>> m = Mock()
>>> m.hello.assert_not_called()
>>> obj = m.hello()
>>> m.hello.assert_not_called()
Traceback (most recent call last):
...
AssertionError: Expected 'hello' to not have been called. Called 1 times.
```
3\.5 新版功能.
`reset_mock`(*\**, *return\_value=False*, *side\_effect=False*)The reset\_mock method resets all the call attributes on a mock object:
```
>>> mock = Mock(return_value=None)
>>> mock('hello')
>>> mock.called
True
>>> mock.reset_mock()
>>> mock.called
False
```
在 3.6 版更改: Added two keyword only argument to the reset\_mock function.
This can be useful where you want to make a series of assertions that reuse the same object. Note that [`reset_mock()`](#unittest.mock.Mock.reset_mock "unittest.mock.Mock.reset_mock") *doesn't* clear the return value, [`side_effect`](#unittest.mock.Mock.side_effect "unittest.mock.Mock.side_effect") or any child attributes you have set using normal assignment by default. In case you want to reset *return\_value* or [`side_effect`](#unittest.mock.Mock.side_effect "unittest.mock.Mock.side_effect"), then pass the corresponding parameter as `True`. Child mocks and the return value mock (if any) are reset as well.
注解
*return\_value*, and [`side_effect`](#unittest.mock.Mock.side_effect "unittest.mock.Mock.side_effect") are keyword only argument.
`mock_add_spec`(*spec*, *spec\_set=False*)Add a spec to a mock. *spec* can either be an object or a list of strings. Only attributes on the *spec* can be fetched as attributes from the mock.
If *spec\_set* is true then only attributes on the spec can be set.
`attach_mock`(*mock*, *attribute*)Attach a mock as an attribute of this one, replacing its name and parent. Calls to the attached mock will be recorded in the [`method_calls`](#unittest.mock.Mock.method_calls "unittest.mock.Mock.method_calls") and [`mock_calls`](#unittest.mock.Mock.mock_calls "unittest.mock.Mock.mock_calls") attributes of this one.
`configure_mock`(*\*\*kwargs*)Set attributes on the mock through keyword arguments.
Attributes plus return values and side effects can be set on child mocks using standard dot notation and unpacking a dictionary in the method call:
```
>>> mock = Mock()
>>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
>>> mock.configure_mock(**attrs)
>>> mock.method()
3
>>> mock.other()
Traceback (most recent call last):
...
KeyError
```
The same thing can be achieved in the constructor call to mocks:
```
>>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
>>> mock = Mock(some_attribute='eggs', **attrs)
>>> mock.some_attribute
'eggs'
>>> mock.method()
3
>>> mock.other()
Traceback (most recent call last):
...
KeyError
```
[`configure_mock()`](#unittest.mock.Mock.configure_mock "unittest.mock.Mock.configure_mock") exists to make it easier to do configuration after the mock has been created.
`__dir__`()[`Mock`](#unittest.mock.Mock "unittest.mock.Mock") objects limit the results of `dir(some_mock)` to useful results. For mocks with a *spec* this includes all the permitted attributes for the mock.
See [`FILTER_DIR`](#unittest.mock.FILTER_DIR "unittest.mock.FILTER_DIR") for what this filtering does, and how to switch it off.
`_get_child_mock`(*\*\*kw*)Create the child mocks for attributes and return value. By default child mocks will be the same type as the parent. Subclasses of Mock may want to override this to customize the way child mocks are made.
For non-callable mocks the callable variant will be used (rather than any custom subclass).
`called`A boolean representing whether or not the mock object has been called:
```
>>> mock = Mock(return_value=None)
>>> mock.called
False
>>> mock()
>>> mock.called
True
```
`call_count`An integer telling you how many times the mock object has been called:
```
>>> mock = Mock(return_value=None)
>>> mock.call_count
0
>>> mock()
>>> mock()
>>> mock.call_count
2
```
`return_value`Set this to configure the value returned by calling the mock:
```
>>> mock = Mock()
>>> mock.return_value = 'fish'
>>> mock()
'fish'
```
The default return value is a mock object and you can configure it in the normal way:
```
>>> mock = Mock()
>>> mock.return_value.attribute = sentinel.Attribute
>>> mock.return_value()
<Mock name='mock()()' id='...'>
>>> mock.return_value.assert_called_with()
```
[`return_value`](#unittest.mock.Mock.return_value "unittest.mock.Mock.return_value") can also be set in the constructor:
```
>>> mock = Mock(return_value=3)
>>> mock.return_value
3
>>> mock()
3
```
`side_effect`This can either be a function to be called when the mock is called, an iterable or an exception (class or instance) to be raised.
If you pass in a function it will be called with same arguments as the mock and unless the function returns the [`DEFAULT`](#unittest.mock.DEFAULT "unittest.mock.DEFAULT") singleton the call to the mock will then return whatever the function returns. If the function returns [`DEFAULT`](#unittest.mock.DEFAULT "unittest.mock.DEFAULT") then the mock will return its normal value (from the [`return_value`](#unittest.mock.Mock.return_value "unittest.mock.Mock.return_value")).
If you pass in an iterable, it is used to retrieve an iterator which must yield a value on every call. This value can either be an exception instance to be raised, or a value to be returned from the call to the mock ([`DEFAULT`](#unittest.mock.DEFAULT "unittest.mock.DEFAULT") handling is identical to the function case).
An example of a mock that raises an exception (to test exception handling of an API):
```
>>> mock = Mock()
>>> mock.side_effect = Exception('Boom!')
>>> mock()
Traceback (most recent call last):
...
Exception: Boom!
```
Using [`side_effect`](#unittest.mock.Mock.side_effect "unittest.mock.Mock.side_effect") to return a sequence of values:
```
>>> mock = Mock()
>>> mock.side_effect = [3, 2, 1]
>>> mock(), mock(), mock()
(3, 2, 1)
```
Using a callable:
```
>>> mock = Mock(return_value=3)
>>> def side_effect(*args, **kwargs):
... return DEFAULT
...
>>> mock.side_effect = side_effect
>>> mock()
3
```
[`side_effect`](#unittest.mock.Mock.side_effect "unittest.mock.Mock.side_effect") can be set in the constructor. Here's an example that adds one to the value the mock is called with and returns it:
```
>>> side_effect = lambda value: value + 1
>>> mock = Mock(side_effect=side_effect)
>>> mock(3)
4
>>> mock(-8)
-7
```
Setting [`side_effect`](#unittest.mock.Mock.side_effect "unittest.mock.Mock.side_effect") to `None` clears it:
```
>>> m = Mock(side_effect=KeyError, return_value=3)
>>> m()
Traceback (most recent call last):
...
KeyError
>>> m.side_effect = None
>>> m()
3
```
`call_args`This is either `None` (if the mock hasn't been called), or the arguments that the mock was last called with. This will be in the form of a tuple: the first member is any ordered arguments the mock was called with (or an empty tuple) and the second member is any keyword arguments (or an empty dictionary).
```
>>> mock = Mock(return_value=None)
>>> print(mock.call_args)
None
>>> mock()
>>> mock.call_args
call()
>>> mock.call_args == ()
True
>>> mock(3, 4)
>>> mock.call_args
call(3, 4)
>>> mock.call_args == ((3, 4),)
True
>>> mock(3, 4, 5, key='fish', next='w00t!')
>>> mock.call_args
call(3, 4, 5, key='fish', next='w00t!')
```
[`call_args`](#unittest.mock.Mock.call_args "unittest.mock.Mock.call_args"), along with members of the lists [`call_args_list`](#unittest.mock.Mock.call_args_list "unittest.mock.Mock.call_args_list"), [`method_calls`](#unittest.mock.Mock.method_calls "unittest.mock.Mock.method_calls") and [`mock_calls`](#unittest.mock.Mock.mock_calls "unittest.mock.Mock.mock_calls") are [`call`](#unittest.mock.call "unittest.mock.call") objects. These are tuples, so they can be unpacked to get at the individual arguments and make more complex assertions. See [calls as tuples](#calls-as-tuples).
`call_args_list`This is a list of all the calls made to the mock object in sequence (so the length of the list is the number of times it has been called). Before any calls have been made it is an empty list. The [`call`](#unittest.mock.call "unittest.mock.call") object can be used for conveniently constructing lists of calls to compare with [`call_args_list`](#unittest.mock.Mock.call_args_list "unittest.mock.Mock.call_args_list").
```
>>> mock = Mock(return_value=None)
>>> mock()
>>> mock(3, 4)
>>> mock(key='fish', next='w00t!')
>>> mock.call_args_list
[call(), call(3, 4), call(key='fish', next='w00t!')]
>>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
>>> mock.call_args_list == expected
True
```
Members of [`call_args_list`](#unittest.mock.Mock.call_args_list "unittest.mock.Mock.call_args_list") are [`call`](#unittest.mock.call "unittest.mock.call") objects. These can be unpacked as tuples to get at the individual arguments. See [calls as tuples](#calls-as-tuples).
`method_calls`As well as tracking calls to themselves, mocks also track calls to methods and attributes, and *their* methods and attributes:
```
>>> mock = Mock()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.property.method.attribute()
<Mock name='mock.property.method.attribute()' id='...'>
>>> mock.method_calls
[call.method(), call.property.method.attribute()]
```
Members of [`method_calls`](#unittest.mock.Mock.method_calls "unittest.mock.Mock.method_calls") are [`call`](#unittest.mock.call "unittest.mock.call") objects. These can be unpacked as tuples to get at the individual arguments. See [calls as tuples](#calls-as-tuples).
`mock_calls`[`mock_calls`](#unittest.mock.Mock.mock_calls "unittest.mock.Mock.mock_calls") records *all* calls to the mock object, its methods, magic methods *and* return value mocks.
```
>>> mock = MagicMock()
>>> result = mock(1, 2, 3)
>>> mock.first(a=3)
<MagicMock name='mock.first()' id='...'>
>>> mock.second()
<MagicMock name='mock.second()' id='...'>
>>> int(mock)
1
>>> result(1)
<MagicMock name='mock()()' id='...'>
>>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
... call.__int__(), call()(1)]
>>> mock.mock_calls == expected
True
```
Members of [`mock_calls`](#unittest.mock.Mock.mock_calls "unittest.mock.Mock.mock_calls") are [`call`](#unittest.mock.call "unittest.mock.call") objects. These can be unpacked as tuples to get at the individual arguments. See [calls as tuples](#calls-as-tuples).
注解
The way [`mock_calls`](#unittest.mock.Mock.mock_calls "unittest.mock.Mock.mock_calls") are recorded means that where nested calls are made, the parameters of ancestor calls are not recorded and so will always compare equal:
```
>>> mock = MagicMock()
>>> mock.top(a=3).bottom()
<MagicMock name='mock.top().bottom()' id='...'>
>>> mock.mock_calls
[call.top(a=3), call.top().bottom()]
>>> mock.mock_calls[-1] == call.top(a=-1).bottom()
True
```
`__class__`Normally the [`__class__`](#unittest.mock.Mock.__class__ "unittest.mock.Mock.__class__") attribute of an object will return its type. For a mock object with a `spec`, `__class__` returns the spec class instead. This allows mock objects to pass [`isinstance()`](functions.xhtml#isinstance "isinstance") tests for the object they are replacing / masquerading as:
```
>>> mock = Mock(spec=3)
>>> isinstance(mock, int)
True
```
[`__class__`](#unittest.mock.Mock.__class__ "unittest.mock.Mock.__class__") is assignable to, this allows a mock to pass an [`isinstance()`](functions.xhtml#isinstance "isinstance") check without forcing you to use a spec:
```
>>> mock = Mock()
>>> mock.__class__ = dict
>>> isinstance(mock, dict)
True
```
*class* `unittest.mock.``NonCallableMock`(*spec=None*, *wraps=None*, *name=None*, *spec\_set=None*, *\*\*kwargs*)A non-callable version of [`Mock`](#unittest.mock.Mock "unittest.mock.Mock"). The constructor parameters have the same meaning of [`Mock`](#unittest.mock.Mock "unittest.mock.Mock"), with the exception of *return\_value* and *side\_effect*which have no meaning on a non-callable mock.
Mock objects that use a class or an instance as a `spec` or `spec_set` are able to pass [`isinstance()`](functions.xhtml#isinstance "isinstance") tests:
```
>>> mock = Mock(spec=SomeClass)
>>> isinstance(mock, SomeClass)
True
>>> mock = Mock(spec_set=SomeClass())
>>> isinstance(mock, SomeClass)
True
```
The [`Mock`](#unittest.mock.Mock "unittest.mock.Mock") classes have support for mocking magic methods. See [magic methods](#magic-methods) for the full details.
The mock classes and the [`patch()`](#unittest.mock.patch "unittest.mock.patch") decorators all take arbitrary keyword arguments for configuration. For the [`patch()`](#unittest.mock.patch "unittest.mock.patch") decorators the keywords are passed to the constructor of the mock being created. The keyword arguments are for configuring attributes of the mock:
```
>>> m = MagicMock(attribute=3, other='fish')
>>> m.attribute
3
>>> m.other
'fish'
```
The return value and side effect of child mocks can be set in the same way, using dotted notation. As you can't use dotted names directly in a call you have to create a dictionary and unpack it using `**`:
```
>>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
>>> mock = Mock(some_attribute='eggs', **attrs)
>>> mock.some_attribute
'eggs'
>>> mock.method()
3
>>> mock.other()
Traceback (most recent call last):
...
KeyError
```
A callable mock which was created with a *spec* (or a *spec\_set*) will introspect the specification object's signature when matching calls to the mock. Therefore, it can match the actual call's arguments regardless of whether they were passed positionally or by name:
```
>>> def f(a, b, c): pass
...
>>> mock = Mock(spec=f)
>>> mock(1, 2, c=3)
<Mock name='mock()' id='140161580456576'>
>>> mock.assert_called_with(1, 2, 3)
>>> mock.assert_called_with(a=1, b=2, c=3)
```
This applies to [`assert_called_with()`](#unittest.mock.Mock.assert_called_with "unittest.mock.Mock.assert_called_with"), [`assert_called_once_with()`](#unittest.mock.Mock.assert_called_once_with "unittest.mock.Mock.assert_called_once_with"), [`assert_has_calls()`](#unittest.mock.Mock.assert_has_calls "unittest.mock.Mock.assert_has_calls") and [`assert_any_call()`](#unittest.mock.Mock.assert_any_call "unittest.mock.Mock.assert_any_call"). When [Autospeccing](#auto-speccing), it will also apply to method calls on the mock object.
> 在 3.4 版更改: Added signature introspection on specced and autospecced mock objects.
*class* `unittest.mock.``PropertyMock`(*\*args*, *\*\*kwargs*)A mock intended to be used as a property, or other descriptor, on a class. [`PropertyMock`](#unittest.mock.PropertyMock "unittest.mock.PropertyMock") provides [`__get__()`](../reference/datamodel.xhtml#object.__get__ "object.__get__") and [`__set__()`](../reference/datamodel.xhtml#object.__set__ "object.__set__") methods so you can specify a return value when it is fetched.
Fetching a [`PropertyMock`](#unittest.mock.PropertyMock "unittest.mock.PropertyMock") instance from an object calls the mock, with no args. Setting it calls the mock with the value being set.
```
>>> class Foo:
... @property
... def foo(self):
... return 'something'
... @foo.setter
... def foo(self, value):
... pass
...
>>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
... mock_foo.return_value = 'mockity-mock'
... this_foo = Foo()
... print(this_foo.foo)
... this_foo.foo = 6
...
mockity-mock
>>> mock_foo.mock_calls
[call(), call(6)]
```
Because of the way mock attributes are stored you can't directly attach a [`PropertyMock`](#unittest.mock.PropertyMock "unittest.mock.PropertyMock") to a mock object. Instead you can attach it to the mock type object:
```
>>> m = MagicMock()
>>> p = PropertyMock(return_value=3)
>>> type(m).foo = p
>>> m.foo
3
>>> p.assert_called_once_with()
```
### Calling
Mock objects are callable. The call will return the value set as the [`return_value`](#unittest.mock.Mock.return_value "unittest.mock.Mock.return_value") attribute. The default return value is a new Mock object; it is created the first time the return value is accessed (either explicitly or by calling the Mock) - but it is stored and the same one returned each time.
Calls made to the object will be recorded in the attributes like [`call_args`](#unittest.mock.Mock.call_args "unittest.mock.Mock.call_args") and [`call_args_list`](#unittest.mock.Mock.call_args_list "unittest.mock.Mock.call_args_list").
If [`side_effect`](#unittest.mock.Mock.side_effect "unittest.mock.Mock.side_effect") is set then it will be called after the call has been recorded, so if `side_effect` raises an exception the call is still recorded.
The simplest way to make a mock raise an exception when called is to make [`side_effect`](#unittest.mock.Mock.side_effect "unittest.mock.Mock.side_effect") an exception class or instance:
```
>>> m = MagicMock(side_effect=IndexError)
>>> m(1, 2, 3)
Traceback (most recent call last):
...
IndexError
>>> m.mock_calls
[call(1, 2, 3)]
>>> m.side_effect = KeyError('Bang!')
>>> m('two', 'three', 'four')
Traceback (most recent call last):
...
KeyError: 'Bang!'
>>> m.mock_calls
[call(1, 2, 3), call('two', 'three', 'four')]
```
If `side_effect` is a function then whatever that function returns is what calls to the mock return. The `side_effect` function is called with the same arguments as the mock. This allows you to vary the return value of the call dynamically, based on the input:
```
>>> def side_effect(value):
... return value + 1
...
>>> m = MagicMock(side_effect=side_effect)
>>> m(1)
2
>>> m(2)
3
>>> m.mock_calls
[call(1), call(2)]
```
If you want the mock to still return the default return value (a new mock), or any set return value, then there are two ways of doing this. Either return `mock.return_value` from inside `side_effect`, or return [`DEFAULT`](#unittest.mock.DEFAULT "unittest.mock.DEFAULT"):
```
>>> m = MagicMock()
>>> def side_effect(*args, **kwargs):
... return m.return_value
...
>>> m.side_effect = side_effect
>>> m.return_value = 3
>>> m()
3
>>> def side_effect(*args, **kwargs):
... return DEFAULT
...
>>> m.side_effect = side_effect
>>> m()
3
```
To remove a `side_effect`, and return to the default behaviour, set the `side_effect` to `None`:
```
>>> m = MagicMock(return_value=6)
>>> def side_effect(*args, **kwargs):
... return 3
...
>>> m.side_effect = side_effect
>>> m()
3
>>> m.side_effect = None
>>> m()
6
```
The `side_effect` can also be any iterable object. Repeated calls to the mock will return values from the iterable (until the iterable is exhausted and a [`StopIteration`](exceptions.xhtml#StopIteration "StopIteration") is raised):
```
>>> m = MagicMock(side_effect=[1, 2, 3])
>>> m()
1
>>> m()
2
>>> m()
3
>>> m()
Traceback (most recent call last):
...
StopIteration
```
If any members of the iterable are exceptions they will be raised instead of returned:
```
>>> iterable = (33, ValueError, 66)
>>> m = MagicMock(side_effect=iterable)
>>> m()
33
>>> m()
Traceback (most recent call last):
...
ValueError
>>> m()
66
```
### Deleting Attributes
Mock objects create attributes on demand. This allows them to pretend to be objects of any type.
You may want a mock object to return `False` to a [`hasattr()`](functions.xhtml#hasattr "hasattr") call, or raise an [`AttributeError`](exceptions.xhtml#AttributeError "AttributeError") when an attribute is fetched. You can do this by providing an object as a `spec` for a mock, but that isn't always convenient.
You "block" attributes by deleting them. Once deleted, accessing an attribute will raise an [`AttributeError`](exceptions.xhtml#AttributeError "AttributeError").
```
>>> mock = MagicMock()
>>> hasattr(mock, 'm')
True
>>> del mock.m
>>> hasattr(mock, 'm')
False
>>> del mock.f
>>> mock.f
Traceback (most recent call last):
...
AttributeError: f
```
### Mock names and the name attribute
Since "name" is an argument to the [`Mock`](#unittest.mock.Mock "unittest.mock.Mock") constructor, if you want your mock object to have a "name" attribute you can't just pass it in at creation time. There are two alternatives. One option is to use [`configure_mock()`](#unittest.mock.Mock.configure_mock "unittest.mock.Mock.configure_mock"):
```
>>> mock = MagicMock()
>>> mock.configure_mock(name='my_name')
>>> mock.name
'my_name'
```
A simpler option is to simply set the "name" attribute after mock creation:
```
>>> mock = MagicMock()
>>> mock.name = "foo"
```
### Attaching Mocks as Attributes
When you attach a mock as an attribute of another mock (or as the return value) it becomes a "child" of that mock. Calls to the child are recorded in the [`method_calls`](#unittest.mock.Mock.method_calls "unittest.mock.Mock.method_calls") and [`mock_calls`](#unittest.mock.Mock.mock_calls "unittest.mock.Mock.mock_calls") attributes of the parent. This is useful for configuring child mocks and then attaching them to the parent, or for attaching mocks to a parent that records all calls to the children and allows you to make assertions about the order of calls between mocks:
```
>>> parent = MagicMock()
>>> child1 = MagicMock(return_value=None)
>>> child2 = MagicMock(return_value=None)
>>> parent.child1 = child1
>>> parent.child2 = child2
>>> child1(1)
>>> child2(2)
>>> parent.mock_calls
[call.child1(1), call.child2(2)]
```
The exception to this is if the mock has a name. This allows you to prevent the "parenting" if for some reason you don't want it to happen.
```
>>> mock = MagicMock()
>>> not_a_child = MagicMock(name='not-a-child')
>>> mock.attribute = not_a_child
>>> mock.attribute()
<MagicMock name='not-a-child()' id='...'>
>>> mock.mock_calls
[]
```
Mocks created for you by [`patch()`](#unittest.mock.patch "unittest.mock.patch") are automatically given names. To attach mocks that have names to a parent you use the [`attach_mock()`](#unittest.mock.Mock.attach_mock "unittest.mock.Mock.attach_mock")method:
```
>>> thing1 = object()
>>> thing2 = object()
>>> parent = MagicMock()
>>> with patch('__main__.thing1', return_value=None) as child1:
... with patch('__main__.thing2', return_value=None) as child2:
... parent.attach_mock(child1, 'child1')
... parent.attach_mock(child2, 'child2')
... child1('one')
... child2('two')
...
>>> parent.mock_calls
[call.child1('one'), call.child2('two')]
```
[1](#id1)The only exceptions are magic methods and attributes (those that have leading and trailing double underscores). Mock doesn't create these but instead raises an [`AttributeError`](exceptions.xhtml#AttributeError "AttributeError"). This is because the interpreter will often implicitly request these methods, and gets *very* confused to get a new Mock object when it expects a magic method. If you need magic method support see [magic methods](#magic-methods).
## The patchers
The patch decorators are used for patching objects only within the scope of the function they decorate. They automatically handle the unpatching for you, even if exceptions are raised. All of these functions can also be used in with statements or as class decorators.
### patch
注解
[`patch()`](#unittest.mock.patch "unittest.mock.patch") is straightforward to use. The key is to do the patching in the right namespace. See the section [where to patch](#id5).
`unittest.mock.``patch`(*target*, *new=DEFAULT*, *spec=None*, *create=False*, *spec\_set=None*, *autospec=None*, *new\_callable=None*, *\*\*kwargs*)[`patch()`](#unittest.mock.patch "unittest.mock.patch") acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the *target*is patched with a *new* object. When the function/with statement exits the patch is undone.
If *new* is omitted, then the target is replaced with a [`MagicMock`](#unittest.mock.MagicMock "unittest.mock.MagicMock"). If [`patch()`](#unittest.mock.patch "unittest.mock.patch") is used as a decorator and *new* is omitted, the created mock is passed in as an extra argument to the decorated function. If [`patch()`](#unittest.mock.patch "unittest.mock.patch") is used as a context manager the created mock is returned by the context manager.
*target* should be a string in the form `'package.module.ClassName'`. The *target* is imported and the specified object replaced with the *new*object, so the *target* must be importable from the environment you are calling [`patch()`](#unittest.mock.patch "unittest.mock.patch") from. The target is imported when the decorated function is executed, not at decoration time.
The *spec* and *spec\_set* keyword arguments are passed to the [`MagicMock`](#unittest.mock.MagicMock "unittest.mock.MagicMock")if patch is creating one for you.
In addition you can pass `spec=True` or `spec_set=True`, which causes patch to pass in the object being mocked as the spec/spec\_set object.
*new\_callable* allows you to specify a different class, or callable object, that will be called to create the *new* object. By default [`MagicMock`](#unittest.mock.MagicMock "unittest.mock.MagicMock") is used.
A more powerful form of *spec* is *autospec*. If you set `autospec=True`then the mock will be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. Methods and functions being mocked will have their arguments checked and will raise a [`TypeError`](exceptions.xhtml#TypeError "TypeError") if they are called with the wrong signature. For mocks replacing a class, their return value (the 'instance') will have the same spec as the class. See the [`create_autospec()`](#unittest.mock.create_autospec "unittest.mock.create_autospec") function and [Autospeccing](#auto-speccing).
Instead of `autospec=True` you can pass `autospec=some_object` to use an arbitrary object as the spec instead of the one being replaced.
By default [`patch()`](#unittest.mock.patch "unittest.mock.patch") will fail to replace attributes that don't exist. If you pass in `create=True`, and the attribute doesn't exist, patch will create the attribute for you when the patched function is called, and delete it again after the patched function has exited. This is useful for writing tests against attributes that your production code creates at runtime. It is off by default because it can be dangerous. With it switched on you can write passing tests against APIs that don't actually exist!
注解
在 3.5 版更改: If you are patching builtins in a module then you don't need to pass `create=True`, it will be added by default.
Patch can be used as a `TestCase` class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set. [`patch()`](#unittest.mock.patch "unittest.mock.patch") finds tests by looking for method names that start with `patch.TEST_PREFIX`. By default this is `'test'`, which matches the way [`unittest`](unittest.xhtml#module-unittest "unittest: Unit testing framework for Python.") finds tests. You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
Patch can be used as a context manager, with the with statement. Here the patching applies to the indented block after the with statement. If you use "as" then the patched object will be bound to the name after the "as"; very useful if [`patch()`](#unittest.mock.patch "unittest.mock.patch") is creating a mock object for you.
[`patch()`](#unittest.mock.patch "unittest.mock.patch") takes arbitrary keyword arguments. These will be passed to the [`Mock`](#unittest.mock.Mock "unittest.mock.Mock") (or *new\_callable*) on construction.
`patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are available for alternate use-cases.
[`patch()`](#unittest.mock.patch "unittest.mock.patch") as function decorator, creating the mock for you and passing it into the decorated function:
```
>>> @patch('__main__.SomeClass')
... def function(normal_argument, mock_class):
... print(mock_class is SomeClass)
...
>>> function(None)
True
```
Patching a class replaces the class with a [`MagicMock`](#unittest.mock.MagicMock "unittest.mock.MagicMock") *instance*. If the class is instantiated in the code under test then it will be the [`return_value`](#unittest.mock.Mock.return_value "unittest.mock.Mock.return_value") of the mock that will be used.
If the class is instantiated multiple times you could use [`side_effect`](#unittest.mock.Mock.side_effect "unittest.mock.Mock.side_effect") to return a new mock each time. Alternatively you can set the *return\_value* to be anything you want.
To configure return values on methods of *instances* on the patched class you must do this on the `return_value`. For example:
```
>>> class Class:
... def method(self):
... pass
...
>>> with patch('__main__.Class') as MockClass:
... instance = MockClass.return_value
... instance.method.return_value = 'foo'
... assert Class() is instance
... assert Class().method() == 'foo'
...
```
If you use *spec* or *spec\_set* and [`patch()`](#unittest.mock.patch "unittest.mock.patch") is replacing a *class*, then the return value of the created mock will have the same spec.
```
>>> Original = Class
>>> patcher = patch('__main__.Class', spec=True)
>>> MockClass = patcher.start()
>>> instance = MockClass()
>>> assert isinstance(instance, Original)
>>> patcher.stop()
```
The *new\_callable* argument is useful where you want to use an alternative class to the default [`MagicMock`](#unittest.mock.MagicMock "unittest.mock.MagicMock") for the created mock. For example, if you wanted a [`NonCallableMock`](#unittest.mock.NonCallableMock "unittest.mock.NonCallableMock") to be used:
```
>>> thing = object()
>>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
... assert thing is mock_thing
... thing()
...
Traceback (most recent call last):
...
TypeError: 'NonCallableMock' object is not callable
```
Another use case might be to replace an object with an [`io.StringIO`](io.xhtml#io.StringIO "io.StringIO") instance:
```
>>> from io import StringIO
>>> def foo():
... print('Something')
...
>>> @patch('sys.stdout', new_callable=StringIO)
... def test(mock_stdout):
... foo()
... assert mock_stdout.getvalue() == 'Something\n'
...
>>> test()
```
When [`patch()`](#unittest.mock.patch "unittest.mock.patch") is creating a mock for you, it is common that the first thing you need to do is to configure the mock. Some of that configuration can be done in the call to patch. Any arbitrary keywords you pass into the call will be used to set attributes on the created mock:
```
>>> patcher = patch('__main__.thing', first='one', second='two')
>>> mock_thing = patcher.start()
>>> mock_thing.first
'one'
>>> mock_thing.second
'two'
```
As well as attributes on the created mock attributes, like the [`return_value`](#unittest.mock.Mock.return_value "unittest.mock.Mock.return_value") and [`side_effect`](#unittest.mock.Mock.side_effect "unittest.mock.Mock.side_effect"), of child mocks can also be configured. These aren't syntactically valid to pass in directly as keyword arguments, but a dictionary with these as keys can still be expanded into a [`patch()`](#unittest.mock.patch "unittest.mock.patch") call using `**`:
```
>>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
>>> patcher = patch('__main__.thing', **config)
>>> mock_thing = patcher.start()
>>> mock_thing.method()
3
>>> mock_thing.other()
Traceback (most recent call last):
...
KeyError
```
By default, attempting to patch a function in a module (or a method or an attribute in a class) that does not exist will fail with [`AttributeError`](exceptions.xhtml#AttributeError "AttributeError"):
```
>>> @patch('sys.non_existing_attribute', 42)
... def test():
... assert sys.non_existing_attribute == 42
...
>>> test()
Traceback (most recent call last):
...
AttributeError: <module 'sys' (built-in)> does not have the attribute 'non_existing'
```
but adding `create=True` in the call to [`patch()`](#unittest.mock.patch "unittest.mock.patch") will make the previous example work as expected:
```
>>> @patch('sys.non_existing_attribute', 42, create=True)
... def test(mock_stdout):
... assert sys.non_existing_attribute == 42
...
>>> test()
```
### patch.object
`patch.``object`(*target*, *attribute*, *new=DEFAULT*, *spec=None*, *create=False*, *spec\_set=None*, *autospec=None*, *new\_callable=None*, *\*\*kwargs*)patch the named member (*attribute*) on an object (*target*) with a mock object.
[`patch.object()`](#unittest.mock.patch.object "unittest.mock.patch.object") can be used as a decorator, class decorator or a context manager. Arguments *new*, *spec*, *create*, *spec\_set*, *autospec* and *new\_callable* have the same meaning as for [`patch()`](#unittest.mock.patch "unittest.mock.patch"). Like [`patch()`](#unittest.mock.patch "unittest.mock.patch"), [`patch.object()`](#unittest.mock.patch.object "unittest.mock.patch.object") takes arbitrary keyword arguments for configuring the mock object it creates.
When used as a class decorator [`patch.object()`](#unittest.mock.patch.object "unittest.mock.patch.object") honours `patch.TEST_PREFIX`for choosing which methods to wrap.
You can either call [`patch.object()`](#unittest.mock.patch.object "unittest.mock.patch.object") with three arguments or two arguments. The three argument form takes the object to be patched, the attribute name and the object to replace the attribute with.
When calling with the two argument form you omit the replacement object, and a mock is created for you and passed in as an extra argument to the decorated function:
```
>>> @patch.object(SomeClass, 'class_method')
... def test(mock_method):
... SomeClass.class_method(3)
... mock_method.assert_called_with(3)
...
>>> test()
```
*spec*, *create* and the other arguments to [`patch.object()`](#unittest.mock.patch.object "unittest.mock.patch.object") have the same meaning as they do for [`patch()`](#unittest.mock.patch "unittest.mock.patch").
### patch.dict
`patch.``dict`(*in\_dict*, *values=()*, *clear=False*, *\*\*kwargs*)Patch a dictionary, or dictionary like object, and restore the dictionary to its original state after the test.
*in\_dict* can be a dictionary or a mapping like container. If it is a mapping then it must at least support getting, setting and deleting items plus iterating over keys.
*in\_dict* can also be a string specifying the name of the dictionary, which will then be fetched by importing it.
*values* can be a dictionary of values to set in the dictionary. *values*can also be an iterable of `(key, value)` pairs.
If *clear* is true then the dictionary will be cleared before the new values are set.
[`patch.dict()`](#unittest.mock.patch.dict "unittest.mock.patch.dict") can also be called with arbitrary keyword arguments to set values in the dictionary.
[`patch.dict()`](#unittest.mock.patch.dict "unittest.mock.patch.dict") can be used as a context manager, decorator or class decorator. When used as a class decorator [`patch.dict()`](#unittest.mock.patch.dict "unittest.mock.patch.dict") honours `patch.TEST_PREFIX` for choosing which methods to wrap.
[`patch.dict()`](#unittest.mock.patch.dict "unittest.mock.patch.dict") can be used to add members to a dictionary, or simply let a test change a dictionary, and ensure the dictionary is restored when the test ends.
```
>>> foo = {}
>>> with patch.dict(foo, {'newkey': 'newvalue'}):
... assert foo == {'newkey': 'newvalue'}
...
>>> assert foo == {}
```
```
>>> import os
>>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
... print(os.environ['newkey'])
...
newvalue
>>> assert 'newkey' not in os.environ
```
Keywords can be used in the [`patch.dict()`](#unittest.mock.patch.dict "unittest.mock.patch.dict") call to set values in the dictionary:
```
>>> mymodule = MagicMock()
>>> mymodule.function.return_value = 'fish'
>>> with patch.dict('sys.modules', mymodule=mymodule):
... import mymodule
... mymodule.function('some', 'args')
...
'fish'
```
[`patch.dict()`](#unittest.mock.patch.dict "unittest.mock.patch.dict") can be used with dictionary like objects that aren't actually dictionaries. At the very minimum they must support item getting, setting, deleting and either iteration or membership test. This corresponds to the magic methods [`__getitem__()`](../reference/datamodel.xhtml#object.__getitem__ "object.__getitem__"), [`__setitem__()`](../reference/datamodel.xhtml#object.__setitem__ "object.__setitem__"), [`__delitem__()`](../reference/datamodel.xhtml#object.__delitem__ "object.__delitem__") and either [`__iter__()`](../reference/datamodel.xhtml#object.__iter__ "object.__iter__") or [`__contains__()`](../reference/datamodel.xhtml#object.__contains__ "object.__contains__").
```
>>> class Container:
... def __init__(self):
... self.values = {}
... def __getitem__(self, name):
... return self.values[name]
... def __setitem__(self, name, value):
... self.values[name] = value
... def __delitem__(self, name):
... del self.values[name]
... def __iter__(self):
... return iter(self.values)
...
>>> thing = Container()
>>> thing['one'] = 1
>>> with patch.dict(thing, one=2, two=3):
... assert thing['one'] == 2
... assert thing['two'] == 3
...
>>> assert thing['one'] == 1
>>> assert list(thing) == ['one']
```
### patch.multiple
`patch.``multiple`(*target*, *spec=None*, *create=False*, *spec\_set=None*, *autospec=None*, *new\_callable=None*, *\*\*kwargs*)Perform multiple patches in a single call. It takes the object to be patched (either as an object or a string to fetch the object by importing) and keyword arguments for the patches:
```
with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
...
```
Use [`DEFAULT`](#unittest.mock.DEFAULT "unittest.mock.DEFAULT") as the value if you want [`patch.multiple()`](#unittest.mock.patch.multiple "unittest.mock.patch.multiple") to create mocks for you. In this case the created mocks are passed into a decorated function by keyword, and a dictionary is returned when [`patch.multiple()`](#unittest.mock.patch.multiple "unittest.mock.patch.multiple") is used as a context manager.
[`patch.multiple()`](#unittest.mock.patch.multiple "unittest.mock.patch.multiple") can be used as a decorator, class decorator or a context manager. The arguments *spec*, *spec\_set*, *create*, *autospec* and *new\_callable* have the same meaning as for [`patch()`](#unittest.mock.patch "unittest.mock.patch"). These arguments will be applied to *all* patches done by [`patch.multiple()`](#unittest.mock.patch.multiple "unittest.mock.patch.multiple").
When used as a class decorator [`patch.multiple()`](#unittest.mock.patch.multiple "unittest.mock.patch.multiple") honours `patch.TEST_PREFIX`for choosing which methods to wrap.
If you want [`patch.multiple()`](#unittest.mock.patch.multiple "unittest.mock.patch.multiple") to create mocks for you, then you can use [`DEFAULT`](#unittest.mock.DEFAULT "unittest.mock.DEFAULT") as the value. If you use [`patch.multiple()`](#unittest.mock.patch.multiple "unittest.mock.patch.multiple") as a decorator then the created mocks are passed into the decorated function by keyword.
```
>>> thing = object()
>>> other = object()
```
```
>>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
... def test_function(thing, other):
... assert isinstance(thing, MagicMock)
... assert isinstance(other, MagicMock)
...
>>> test_function()
```
[`patch.multiple()`](#unittest.mock.patch.multiple "unittest.mock.patch.multiple") can be nested with other `patch` decorators, but put arguments passed by keyword *after* any of the standard arguments created by [`patch()`](#unittest.mock.patch "unittest.mock.patch"):
```
>>> @patch('sys.exit')
... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
... def test_function(mock_exit, other, thing):
... assert 'other' in repr(other)
... assert 'thing' in repr(thing)
... assert 'exit' in repr(mock_exit)
...
>>> test_function()
```
If [`patch.multiple()`](#unittest.mock.patch.multiple "unittest.mock.patch.multiple") is used as a context manager, the value returned by the context manager is a dictionary where created mocks are keyed by name:
```
>>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
... assert 'other' in repr(values['other'])
... assert 'thing' in repr(values['thing'])
... assert values['thing'] is thing
... assert values['other'] is other
...
```
### patch methods: start and stop
All the patchers have `start()` and `stop()` methods. These make it simpler to do patching in `setUp` methods or where you want to do multiple patches without nesting decorators or with statements.
To use them call [`patch()`](#unittest.mock.patch "unittest.mock.patch"), [`patch.object()`](#unittest.mock.patch.object "unittest.mock.patch.object") or [`patch.dict()`](#unittest.mock.patch.dict "unittest.mock.patch.dict") as normal and keep a reference to the returned `patcher` object. You can then call `start()` to put the patch in place and `stop()` to undo it.
If you are using [`patch()`](#unittest.mock.patch "unittest.mock.patch") to create a mock for you then it will be returned by the call to `patcher.start`.
```
>>> patcher = patch('package.module.ClassName')
>>> from package import module
>>> original = module.ClassName
>>> new_mock = patcher.start()
>>> assert module.ClassName is not original
>>> assert module.ClassName is new_mock
>>> patcher.stop()
>>> assert module.ClassName is original
>>> assert module.ClassName is not new_mock
```
A typical use case for this might be for doing multiple patches in the `setUp`method of a `TestCase`:
```
>>> class MyTest(TestCase):
... def setUp(self):
... self.patcher1 = patch('package.module.Class1')
... self.patcher2 = patch('package.module.Class2')
... self.MockClass1 = self.patcher1.start()
... self.MockClass2 = self.patcher2.start()
...
... def tearDown(self):
... self.patcher1.stop()
... self.patcher2.stop()
...
... def test_something(self):
... assert package.module.Class1 is self.MockClass1
... assert package.module.Class2 is self.MockClass2
...
>>> MyTest('test_something').run()
```
警告
If you use this technique you must ensure that the patching is "undone" by calling `stop`. This can be fiddlier than you might think, because if an exception is raised in the `setUp` then `tearDown` is not called. [`unittest.TestCase.addCleanup()`](unittest.xhtml#unittest.TestCase.addCleanup "unittest.TestCase.addCleanup") makes this easier:
```
>>> class MyTest(TestCase):
... def setUp(self):
... patcher = patch('package.module.Class')
... self.MockClass = patcher.start()
... self.addCleanup(patcher.stop)
...
... def test_something(self):
... assert package.module.Class is self.MockClass
...
```
As an added bonus you no longer need to keep a reference to the `patcher`object.
It is also possible to stop all patches which have been started by using [`patch.stopall()`](#unittest.mock.patch.stopall "unittest.mock.patch.stopall").
`patch.``stopall`()Stop all active patches. Only stops patches started with `start`.
### patch builtins
You can patch any builtins within a module. The following example patches builtin [`ord()`](functions.xhtml#ord "ord"):
```
>>> @patch('__main__.ord')
... def test(mock_ord):
... mock_ord.return_value = 101
... print(ord('c'))
...
>>> test()
101
```
### TEST\_PREFIX
All of the patchers can be used as class decorators. When used in this way they wrap every test method on the class. The patchers recognise methods that start with `'test'` as being test methods. This is the same way that the [`unittest.TestLoader`](unittest.xhtml#unittest.TestLoader "unittest.TestLoader") finds test methods by default.
It is possible that you want to use a different prefix for your tests. You can inform the patchers of the different prefix by setting `patch.TEST_PREFIX`:
```
>>> patch.TEST_PREFIX = 'foo'
>>> value = 3
>>>
>>> @patch('__main__.value', 'not three')
... class Thing:
... def foo_one(self):
... print(value)
... def foo_two(self):
... print(value)
...
>>>
>>> Thing().foo_one()
not three
>>> Thing().foo_two()
not three
>>> value
3
```
### Nesting Patch Decorators
If you want to perform multiple patches then you can simply stack up the decorators.
You can stack up multiple patch decorators using this pattern:
```
>>> @patch.object(SomeClass, 'class_method')
... @patch.object(SomeClass, 'static_method')
... def test(mock1, mock2):
... assert SomeClass.static_method is mock1
... assert SomeClass.class_method is mock2
... SomeClass.static_method('foo')
... SomeClass.class_method('bar')
... return mock1, mock2
...
>>> mock1, mock2 = test()
>>> mock1.assert_called_once_with('foo')
>>> mock2.assert_called_once_with('bar')
```
Note that the decorators are applied from the bottom upwards. This is the standard way that Python applies decorators. The order of the created mocks passed into your test function matches this order.
### Where to patch
[`patch()`](#unittest.mock.patch "unittest.mock.patch") works by (temporarily) changing the object that a *name* points to with another one. There can be many names pointing to any individual object, so for patching to work you must ensure that you patch the name used by the system under test.
The basic principle is that you patch where an object is *looked up*, which is not necessarily the same place as where it is defined. A couple of examples will help to clarify this.
Imagine we have a project that we want to test with the following structure:
```
a.py
-> Defines SomeClass
b.py
-> from a import SomeClass
-> some_function instantiates SomeClass
```
Now we want to test `some_function` but we want to mock out `SomeClass` using [`patch()`](#unittest.mock.patch "unittest.mock.patch"). The problem is that when we import module b, which we will have to do then it imports `SomeClass` from module a. If we use [`patch()`](#unittest.mock.patch "unittest.mock.patch") to mock out `a.SomeClass` then it will have no effect on our test; module b already has a reference to the *real*`SomeClass` and it looks like our patching had no effect.
The key is to patch out `SomeClass` where it is used (or where it is looked up). In this case `some_function` will actually look up `SomeClass` in module b, where we have imported it. The patching should look like:
```
@patch('b.SomeClass')
```
However, consider the alternative scenario where instead of
```
from a import
SomeClass
```
module b does `import a` and `some_function` uses `a.SomeClass`. Both of these import forms are common. In this case the class we want to patch is being looked up in the module and so we have to patch `a.SomeClass` instead:
```
@patch('a.SomeClass')
```
### Patching Descriptors and Proxy Objects
Both [patch](#patch) and [patch.object](#patch-object) correctly patch and restore descriptors: class methods, static methods and properties. You should patch these on the *class*rather than an instance. They also work with *some* objects that proxy attribute access, like the [django settings object](http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198) \[http://www.voidspace.org.uk/python/weblog/arch\_d7\_2010\_12\_04.shtml#e1198\].
## MagicMock and magic method support
### Mocking Magic Methods
[`Mock`](#unittest.mock.Mock "unittest.mock.Mock") supports mocking the Python protocol methods, also known as "magic methods". This allows mock objects to replace containers or other objects that implement Python protocols.
Because magic methods are looked up differently from normal methods [2](#id8), this support has been specially implemented. This means that only specific magic methods are supported. The supported list includes *almost* all of them. If there are any missing that you need please let us know.
You mock magic methods by setting the method you are interested in to a function or a mock instance. If you are using a function then it *must* take `self` as the first argument [3](#id9).
```
>>> def __str__(self):
... return 'fooble'
...
>>> mock = Mock()
>>> mock.__str__ = __str__
>>> str(mock)
'fooble'
```
```
>>> mock = Mock()
>>> mock.__str__ = Mock()
>>> mock.__str__.return_value = 'fooble'
>>> str(mock)
'fooble'
```
```
>>> mock = Mock()
>>> mock.__iter__ = Mock(return_value=iter([]))
>>> list(mock)
[]
```
One use case for this is for mocking objects used as context managers in a [`with`](../reference/compound_stmts.xhtml#with) statement:
```
>>> mock = Mock()
>>> mock.__enter__ = Mock(return_value='foo')
>>> mock.__exit__ = Mock(return_value=False)
>>> with mock as m:
... assert m == 'foo'
...
>>> mock.__enter__.assert_called_with()
>>> mock.__exit__.assert_called_with(None, None, None)
```
Calls to magic methods do not appear in [`method_calls`](#unittest.mock.Mock.method_calls "unittest.mock.Mock.method_calls"), but they are recorded in [`mock_calls`](#unittest.mock.Mock.mock_calls "unittest.mock.Mock.mock_calls").
注解
If you use the *spec* keyword argument to create a mock then attempting to set a magic method that isn't in the spec will raise an [`AttributeError`](exceptions.xhtml#AttributeError "AttributeError").
The full list of supported magic methods is:
- `__hash__`, `__sizeof__`, `__repr__` and `__str__`
- `__dir__`, `__format__` and `__subclasses__`
- `__floor__`, `__trunc__` and `__ceil__`
- Comparisons: `__lt__`, `__gt__`, `__le__`, `__ge__`, `__eq__` and `__ne__`
- Container methods: `__getitem__`, `__setitem__`, `__delitem__`, `__contains__`, `__len__`, `__iter__`, `__reversed__`and `__missing__`
- Context manager: `__enter__` and `__exit__`
- Unary numeric methods: `__neg__`, `__pos__` and `__invert__`
- The numeric methods (including right hand and in-place variants): `__add__`, `__sub__`, `__mul__`, `__matmul__`, `__div__`, `__truediv__`, `__floordiv__`, `__mod__`, `__divmod__`, `__lshift__`, `__rshift__`, `__and__`, `__xor__`, `__or__`, and `__pow__`
- Numeric conversion methods: `__complex__`, `__int__`, `__float__`and `__index__`
- Descriptor methods: `__get__`, `__set__` and `__delete__`
- Pickling: `__reduce__`, `__reduce_ex__`, `__getinitargs__`, `__getnewargs__`, `__getstate__` and `__setstate__`
The following methods exist but are *not* supported as they are either in use by mock, can't be set dynamically, or can cause problems:
- `__getattr__`, `__setattr__`, `__init__` and `__new__`
- `__prepare__`, `__instancecheck__`, `__subclasscheck__`, `__del__`
### Magic Mock
There are two `MagicMock` variants: [`MagicMock`](#unittest.mock.MagicMock "unittest.mock.MagicMock") and [`NonCallableMagicMock`](#unittest.mock.NonCallableMagicMock "unittest.mock.NonCallableMagicMock").
*class* `unittest.mock.``MagicMock`(*\*args*, *\*\*kw*)`MagicMock` is a subclass of [`Mock`](#unittest.mock.Mock "unittest.mock.Mock") with default implementations of most of the magic methods. You can use `MagicMock` without having to configure the magic methods yourself.
The constructor parameters have the same meaning as for [`Mock`](#unittest.mock.Mock "unittest.mock.Mock").
If you use the *spec* or *spec\_set* arguments then *only* magic methods that exist in the spec will be created.
*class* `unittest.mock.``NonCallableMagicMock`(*\*args*, *\*\*kw*)A non-callable version of [`MagicMock`](#unittest.mock.MagicMock "unittest.mock.MagicMock").
The constructor parameters have the same meaning as for [`MagicMock`](#unittest.mock.MagicMock "unittest.mock.MagicMock"), with the exception of *return\_value* and *side\_effect* which have no meaning on a non-callable mock.
The magic methods are setup with [`MagicMock`](#unittest.mock.MagicMock "unittest.mock.MagicMock") objects, so you can configure them and use them in the usual way:
```
>>> mock = MagicMock()
>>> mock[3] = 'fish'
>>> mock.__setitem__.assert_called_with(3, 'fish')
>>> mock.__getitem__.return_value = 'result'
>>> mock[2]
'result'
```
By default many of the protocol methods are required to return objects of a specific type. These methods are preconfigured with a default return value, so that they can be used without you having to do anything if you aren't interested in the return value. You can still *set* the return value manually if you want to change the default.
Methods and their defaults:
- `__lt__`: NotImplemented
- `__gt__`: NotImplemented
- `__le__`: NotImplemented
- `__ge__`: NotImplemented
- `__int__`: 1
- `__contains__`: False
- `__len__`: 0
- `__iter__`: iter(\[\])
- `__exit__`: False
- `__complex__`: 1j
- `__float__`: 1.0
- `__bool__`: True
- `__index__`: 1
- `__hash__`: default hash for the mock
- `__str__`: default str for the mock
- `__sizeof__`: default sizeof for the mock
例如:
```
>>> mock = MagicMock()
>>> int(mock)
1
>>> len(mock)
0
>>> list(mock)
[]
>>> object() in mock
False
```
The two equality methods, [`__eq__()`](../reference/datamodel.xhtml#object.__eq__ "object.__eq__") and [`__ne__()`](../reference/datamodel.xhtml#object.__ne__ "object.__ne__"), are special. They do the default equality comparison on identity, using the [`side_effect`](#unittest.mock.Mock.side_effect "unittest.mock.Mock.side_effect") attribute, unless you change their return value to return something else:
```
>>> MagicMock() == 3
False
>>> MagicMock() != 3
True
>>> mock = MagicMock()
>>> mock.__eq__.return_value = True
>>> mock == 3
True
```
The return value of `MagicMock.__iter__()` can be any iterable object and isn't required to be an iterator:
```
>>> mock = MagicMock()
>>> mock.__iter__.return_value = ['a', 'b', 'c']
>>> list(mock)
['a', 'b', 'c']
>>> list(mock)
['a', 'b', 'c']
```
If the return value *is* an iterator, then iterating over it once will consume it and subsequent iterations will result in an empty list:
```
>>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
>>> list(mock)
['a', 'b', 'c']
>>> list(mock)
[]
```
`MagicMock` has all of the supported magic methods configured except for some of the obscure and obsolete ones. You can still set these up if you want.
Magic methods that are supported but not setup by default in `MagicMock` are:
- `__subclasses__`
- `__dir__`
- `__format__`
- `__get__`, `__set__` and `__delete__`
- `__reversed__` and `__missing__`
- `__reduce__`, `__reduce_ex__`, `__getinitargs__`, `__getnewargs__`, `__getstate__` and `__setstate__`
- `__getformat__` and `__setformat__`
[2](#id6)Magic methods *should* be looked up on the class rather than the instance. Different versions of Python are inconsistent about applying this rule. The supported protocol methods should work with all supported versions of Python.
[3](#id7)The function is basically hooked up to the class, but each `Mock`instance is kept isolated from the others.
## Helpers
### sentinel
`unittest.mock.``sentinel`The `sentinel` object provides a convenient way of providing unique objects for your tests.
Attributes are created on demand when you access them by name. Accessing the same attribute will always return the same object. The objects returned have a sensible repr so that test failure messages are readable.
在 3.7 版更改: The `sentinel` attributes now preserve their identity when they are [`copied`](copy.xhtml#module-copy "copy: Shallow and deep copy operations.") or [`pickled`](pickle.xhtml#module-pickle "pickle: Convert Python objects to streams of bytes and back.").
Sometimes when testing you need to test that a specific object is passed as an argument to another method, or returned. It can be common to create named sentinel objects to test this. [`sentinel`](#unittest.mock.sentinel "unittest.mock.sentinel") provides a convenient way of creating and testing the identity of objects like this.
In this example we monkey patch `method` to return `sentinel.some_object`:
```
>>> real = ProductionClass()
>>> real.method = Mock(name="method")
>>> real.method.return_value = sentinel.some_object
>>> result = real.method()
>>> assert result is sentinel.some_object
>>> sentinel.some_object
sentinel.some_object
```
### DEFAULT
`unittest.mock.``DEFAULT`The [`DEFAULT`](#unittest.mock.DEFAULT "unittest.mock.DEFAULT") object is a pre-created sentinel (actually `sentinel.DEFAULT`). It can be used by [`side_effect`](#unittest.mock.Mock.side_effect "unittest.mock.Mock.side_effect")functions to indicate that the normal return value should be used.
### call
`unittest.mock.``call`(*\*args*, *\*\*kwargs*)[`call()`](#unittest.mock.call "unittest.mock.call") is a helper object for making simpler assertions, for comparing with [`call_args`](#unittest.mock.Mock.call_args "unittest.mock.Mock.call_args"), [`call_args_list`](#unittest.mock.Mock.call_args_list "unittest.mock.Mock.call_args_list"), [`mock_calls`](#unittest.mock.Mock.mock_calls "unittest.mock.Mock.mock_calls") and [`method_calls`](#unittest.mock.Mock.method_calls "unittest.mock.Mock.method_calls"). [`call()`](#unittest.mock.call "unittest.mock.call") can also be used with [`assert_has_calls()`](#unittest.mock.Mock.assert_has_calls "unittest.mock.Mock.assert_has_calls").
```
>>> m = MagicMock(return_value=None)
>>> m(1, 2, a='foo', b='bar')
>>> m()
>>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
True
```
`call.``call_list`()For a call object that represents multiple calls, [`call_list()`](#unittest.mock.call.call_list "unittest.mock.call.call_list")returns a list of all the intermediate calls as well as the final call.
`call_list` is particularly useful for making assertions on "chained calls". A chained call is multiple calls on a single line of code. This results in multiple entries in [`mock_calls`](#unittest.mock.Mock.mock_calls "unittest.mock.Mock.mock_calls") on a mock. Manually constructing the sequence of calls can be tedious.
[`call_list()`](#unittest.mock.call.call_list "unittest.mock.call.call_list") can construct the sequence of calls from the same chained call:
```
>>> m = MagicMock()
>>> m(1).method(arg='foo').other('bar')(2.0)
<MagicMock name='mock().method().other()()' id='...'>
>>> kall = call(1).method(arg='foo').other('bar')(2.0)
>>> kall.call_list()
[call(1),
call().method(arg='foo'),
call().method().other('bar'),
call().method().other()(2.0)]
>>> m.mock_calls == kall.call_list()
True
```
A `call` object is either a tuple of (positional args, keyword args) or (name, positional args, keyword args) depending on how it was constructed. When you construct them yourself this isn't particularly interesting, but the `call`objects that are in the [`Mock.call_args`](#unittest.mock.Mock.call_args "unittest.mock.Mock.call_args"), [`Mock.call_args_list`](#unittest.mock.Mock.call_args_list "unittest.mock.Mock.call_args_list") and [`Mock.mock_calls`](#unittest.mock.Mock.mock_calls "unittest.mock.Mock.mock_calls") attributes can be introspected to get at the individual arguments they contain.
The `call` objects in [`Mock.call_args`](#unittest.mock.Mock.call_args "unittest.mock.Mock.call_args") and [`Mock.call_args_list`](#unittest.mock.Mock.call_args_list "unittest.mock.Mock.call_args_list")are two-tuples of (positional args, keyword args) whereas the `call` objects in [`Mock.mock_calls`](#unittest.mock.Mock.mock_calls "unittest.mock.Mock.mock_calls"), along with ones you construct yourself, are three-tuples of (name, positional args, keyword args).
You can use their "tupleness" to pull out the individual arguments for more complex introspection and assertions. The positional arguments are a tuple (an empty tuple if there are no positional arguments) and the keyword arguments are a dictionary:
```
>>> m = MagicMock(return_value=None)
>>> m(1, 2, 3, arg='one', arg2='two')
>>> kall = m.call_args
>>> args, kwargs = kall
>>> args
(1, 2, 3)
>>> kwargs
{'arg2': 'two', 'arg': 'one'}
>>> args is kall[0]
True
>>> kwargs is kall[1]
True
```
```
>>> m = MagicMock()
>>> m.foo(4, 5, 6, arg='two', arg2='three')
<MagicMock name='mock.foo()' id='...'>
>>> kall = m.mock_calls[0]
>>> name, args, kwargs = kall
>>> name
'foo'
>>> args
(4, 5, 6)
>>> kwargs
{'arg2': 'three', 'arg': 'two'}
>>> name is m.mock_calls[0][0]
True
```
### create\_autospec
`unittest.mock.``create_autospec`(*spec*, *spec\_set=False*, *instance=False*, *\*\*kwargs*)Create a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the *spec* object as their spec.
Functions or methods being mocked will have their arguments checked to ensure that they are called with the correct signature.
If *spec\_set* is `True` then attempting to set attributes that don't exist on the spec object will raise an [`AttributeError`](exceptions.xhtml#AttributeError "AttributeError").
If a class is used as a spec then the return value of the mock (the instance of the class) will have the same spec. You can use a class as the spec for an instance object by passing `instance=True`. The returned mock will only be callable if instances of the mock are callable.
[`create_autospec()`](#unittest.mock.create_autospec "unittest.mock.create_autospec") also takes arbitrary keyword arguments that are passed to the constructor of the created mock.
See [Autospeccing](#auto-speccing) for examples of how to use auto-speccing with [`create_autospec()`](#unittest.mock.create_autospec "unittest.mock.create_autospec") and the *autospec* argument to [`patch()`](#unittest.mock.patch "unittest.mock.patch").
### ANY
`unittest.mock.``ANY`Sometimes you may need to make assertions about *some* of the arguments in a call to mock, but either not care about some of the arguments or want to pull them individually out of [`call_args`](#unittest.mock.Mock.call_args "unittest.mock.Mock.call_args") and make more complex assertions on them.
To ignore certain arguments you can pass in objects that compare equal to *everything*. Calls to [`assert_called_with()`](#unittest.mock.Mock.assert_called_with "unittest.mock.Mock.assert_called_with") and [`assert_called_once_with()`](#unittest.mock.Mock.assert_called_once_with "unittest.mock.Mock.assert_called_once_with") will then succeed no matter what was passed in.
```
>>> mock = Mock(return_value=None)
>>> mock('foo', bar=object())
>>> mock.assert_called_once_with('foo', bar=ANY)
```
[`ANY`](#unittest.mock.ANY "unittest.mock.ANY") can also be used in comparisons with call lists like [`mock_calls`](#unittest.mock.Mock.mock_calls "unittest.mock.Mock.mock_calls"):
```
>>> m = MagicMock(return_value=None)
>>> m(1)
>>> m(1, 2)
>>> m(object())
>>> m.mock_calls == [call(1), call(1, 2), ANY]
True
```
### FILTER\_DIR
`unittest.mock.``FILTER_DIR`[`FILTER_DIR`](#unittest.mock.FILTER_DIR "unittest.mock.FILTER_DIR") is a module level variable that controls the way mock objects respond to [`dir()`](functions.xhtml#dir "dir") (only for Python 2.6 or more recent). The default is `True`, which uses the filtering described below, to only show useful members. If you dislike this filtering, or need to switch it off for diagnostic purposes, then set `mock.FILTER_DIR = False`.
With filtering on, `dir(some_mock)` shows only useful attributes and will include any dynamically created attributes that wouldn't normally be shown. If the mock was created with a *spec* (or *autospec* of course) then all the attributes from the original are shown, even if they haven't been accessed yet:
```
>>> dir(Mock())
['assert_any_call',
'assert_called_once_with',
'assert_called_with',
'assert_has_calls',
'attach_mock',
...
>>> from urllib import request
>>> dir(Mock(spec=request))
['AbstractBasicAuthHandler',
'AbstractDigestAuthHandler',
'AbstractHTTPHandler',
'BaseHandler',
...
```
Many of the not-very-useful (private to [`Mock`](#unittest.mock.Mock "unittest.mock.Mock") rather than the thing being mocked) underscore and double underscore prefixed attributes have been filtered from the result of calling [`dir()`](functions.xhtml#dir "dir") on a [`Mock`](#unittest.mock.Mock "unittest.mock.Mock"). If you dislike this behaviour you can switch it off by setting the module level switch [`FILTER_DIR`](#unittest.mock.FILTER_DIR "unittest.mock.FILTER_DIR"):
```
>>> from unittest import mock
>>> mock.FILTER_DIR = False
>>> dir(mock.Mock())
['_NonCallableMock__get_return_value',
'_NonCallableMock__get_side_effect',
'_NonCallableMock__return_value_doc',
'_NonCallableMock__set_return_value',
'_NonCallableMock__set_side_effect',
'__call__',
'__class__',
...
```
Alternatively you can just use `vars(my_mock)` (instance members) and `dir(type(my_mock))` (type members) to bypass the filtering irrespective of `mock.FILTER_DIR`.
### mock\_open
`unittest.mock.``mock_open`(*mock=None*, *read\_data=None*)A helper function to create a mock to replace the use of [`open()`](functions.xhtml#open "open"). It works for [`open()`](functions.xhtml#open "open") called directly or used as a context manager.
The *mock* argument is the mock object to configure. If `None` (the default) then a [`MagicMock`](#unittest.mock.MagicMock "unittest.mock.MagicMock") will be created for you, with the API limited to methods or attributes available on standard file handles.
*read\_data* is a string for the `read()`, [`readline()`](io.xhtml#io.IOBase.readline "io.IOBase.readline"), and [`readlines()`](io.xhtml#io.IOBase.readlines "io.IOBase.readlines") methods of the file handle to return. Calls to those methods will take data from *read\_data* until it is depleted. The mock of these methods is pretty simplistic: every time the *mock* is called, the *read\_data* is rewound to the start. If you need more control over the data that you are feeding to the tested code you will need to customize this mock for yourself. When that is insufficient, one of the in-memory filesystem packages on [PyPI](https://pypi.org) \[https://pypi.org\] can offer a realistic filesystem for testing.
在 3.4 版更改: Added [`readline()`](io.xhtml#io.IOBase.readline "io.IOBase.readline") and [`readlines()`](io.xhtml#io.IOBase.readlines "io.IOBase.readlines") support. The mock of `read()` changed to consume *read\_data* rather than returning it on each call.
在 3.5 版更改: *read\_data* is now reset on each call to the *mock*.
在 3.7.1 版更改: Added [`__iter__()`](../reference/datamodel.xhtml#object.__iter__ "object.__iter__") to implementation so that iteration (such as in for loops) correctly consumes *read\_data*.
Using [`open()`](functions.xhtml#open "open") as a context manager is a great way to ensure your file handles are closed properly and is becoming common:
```
with open('/some/path', 'w') as f:
f.write('something')
```
The issue is that even if you mock out the call to [`open()`](functions.xhtml#open "open") it is the *returned object* that is used as a context manager (and has [`__enter__()`](../reference/datamodel.xhtml#object.__enter__ "object.__enter__") and [`__exit__()`](../reference/datamodel.xhtml#object.__exit__ "object.__exit__") called).
Mocking context managers with a [`MagicMock`](#unittest.mock.MagicMock "unittest.mock.MagicMock") is common enough and fiddly enough that a helper function is useful.
```
>>> m = mock_open()
>>> with patch('__main__.open', m):
... with open('foo', 'w') as h:
... h.write('some stuff')
...
>>> m.mock_calls
[call('foo', 'w'),
call().__enter__(),
call().write('some stuff'),
call().__exit__(None, None, None)]
>>> m.assert_called_once_with('foo', 'w')
>>> handle = m()
>>> handle.write.assert_called_once_with('some stuff')
```
And for reading files:
```
>>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
... with open('foo') as h:
... result = h.read()
...
>>> m.assert_called_once_with('foo')
>>> assert result == 'bibble'
```
### Autospeccing
Autospeccing is based on the existing `spec` feature of mock. It limits the api of mocks to the api of an original object (the spec), but it is recursive (implemented lazily) so that attributes of mocks only have the same api as the attributes of the spec. In addition mocked functions / methods have the same call signature as the original so they raise a [`TypeError`](exceptions.xhtml#TypeError "TypeError") if they are called incorrectly.
Before I explain how auto-speccing works, here's why it is needed.
[`Mock`](#unittest.mock.Mock "unittest.mock.Mock") is a very powerful and flexible object, but it suffers from two flaws when used to mock out objects from a system under test. One of these flaws is specific to the [`Mock`](#unittest.mock.Mock "unittest.mock.Mock") api and the other is a more general problem with using mock objects.
First the problem specific to [`Mock`](#unittest.mock.Mock "unittest.mock.Mock"). [`Mock`](#unittest.mock.Mock "unittest.mock.Mock") has two assert methods that are extremely handy: [`assert_called_with()`](#unittest.mock.Mock.assert_called_with "unittest.mock.Mock.assert_called_with") and [`assert_called_once_with()`](#unittest.mock.Mock.assert_called_once_with "unittest.mock.Mock.assert_called_once_with").
```
>>> mock = Mock(name='Thing', return_value=None)
>>> mock(1, 2, 3)
>>> mock.assert_called_once_with(1, 2, 3)
>>> mock(1, 2, 3)
>>> mock.assert_called_once_with(1, 2, 3)
Traceback (most recent call last):
...
AssertionError: Expected 'mock' to be called once. Called 2 times.
```
Because mocks auto-create attributes on demand, and allow you to call them with arbitrary arguments, if you misspell one of these assert methods then your assertion is gone:
```
>>> mock = Mock(name='Thing', return_value=None)
>>> mock(1, 2, 3)
>>> mock.assret_called_once_with(4, 5, 6)
```
Your tests can pass silently and incorrectly because of the typo.
The second issue is more general to mocking. If you refactor some of your code, rename members and so on, any tests for code that is still using the *old api* but uses mocks instead of the real objects will still pass. This means your tests can all pass even though your code is broken.
Note that this is another reason why you need integration tests as well as unit tests. Testing everything in isolation is all fine and dandy, but if you don't test how your units are "wired together" there is still lots of room for bugs that tests might have caught.
`mock` already provides a feature to help with this, called speccing. If you use a class or instance as the `spec` for a mock then you can only access attributes on the mock that exist on the real class:
```
>>> from urllib import request
>>> mock = Mock(spec=request.Request)
>>> mock.assret_called_with
Traceback (most recent call last):
...
AttributeError: Mock object has no attribute 'assret_called_with'
```
The spec only applies to the mock itself, so we still have the same issue with any methods on the mock:
```
>>> mock.has_data()
<mock.Mock object at 0x...>
>>> mock.has_data.assret_called_with()
```
Auto-speccing solves this problem. You can either pass `autospec=True` to [`patch()`](#unittest.mock.patch "unittest.mock.patch") / [`patch.object()`](#unittest.mock.patch.object "unittest.mock.patch.object") or use the [`create_autospec()`](#unittest.mock.create_autospec "unittest.mock.create_autospec") function to create a mock with a spec. If you use the `autospec=True` argument to [`patch()`](#unittest.mock.patch "unittest.mock.patch") then the object that is being replaced will be used as the spec object. Because the speccing is done "lazily" (the spec is created as attributes on the mock are accessed) you can use it with very complex or deeply nested objects (like modules that import modules that import modules) without a big performance hit.
Here's an example of it in use:
```
>>> from urllib import request
>>> patcher = patch('__main__.request', autospec=True)
>>> mock_request = patcher.start()
>>> request is mock_request
True
>>> mock_request.Request
<MagicMock name='request.Request' spec='Request' id='...'>
```
You can see that `request.Request` has a spec. `request.Request` takes two arguments in the constructor (one of which is *self*). Here's what happens if we try to call it incorrectly:
```
>>> req = request.Request()
Traceback (most recent call last):
...
TypeError: <lambda>() takes at least 2 arguments (1 given)
```
The spec also applies to instantiated classes (i.e. the return value of specced mocks):
```
>>> req = request.Request('foo')
>>> req
<NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
```
`Request` objects are not callable, so the return value of instantiating our mocked out `request.Request` is a non-callable mock. With the spec in place any typos in our asserts will raise the correct error:
```
>>> req.add_header('spam', 'eggs')
<MagicMock name='request.Request().add_header()' id='...'>
>>> req.add_header.assret_called_with
Traceback (most recent call last):
...
AttributeError: Mock object has no attribute 'assret_called_with'
>>> req.add_header.assert_called_with('spam', 'eggs')
```
In many cases you will just be able to add `autospec=True` to your existing [`patch()`](#unittest.mock.patch "unittest.mock.patch") calls and then be protected against bugs due to typos and api changes.
As well as using *autospec* through [`patch()`](#unittest.mock.patch "unittest.mock.patch") there is a [`create_autospec()`](#unittest.mock.create_autospec "unittest.mock.create_autospec") for creating autospecced mocks directly:
```
>>> from urllib import request
>>> mock_request = create_autospec(request)
>>> mock_request.Request('foo', 'bar')
<NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
```
This isn't without caveats and limitations however, which is why it is not the default behaviour. In order to know what attributes are available on the spec object, autospec has to introspect (access attributes) the spec. As you traverse attributes on the mock a corresponding traversal of the original object is happening under the hood. If any of your specced objects have properties or descriptors that can trigger code execution then you may not be able to use autospec. On the other hand it is much better to design your objects so that introspection is safe [4](#id11).
A more serious problem is that it is common for instance attributes to be created in the [`__init__()`](../reference/datamodel.xhtml#object.__init__ "object.__init__") method and not to exist on the class at all. *autospec* can't know about any dynamically created attributes and restricts the api to visible attributes.
```
>>> class Something:
... def __init__(self):
... self.a = 33
...
>>> with patch('__main__.Something', autospec=True):
... thing = Something()
... thing.a
...
Traceback (most recent call last):
...
AttributeError: Mock object has no attribute 'a'
```
There are a few different ways of resolving this problem. The easiest, but not necessarily the least annoying, way is to simply set the required attributes on the mock after creation. Just because *autospec* doesn't allow you to fetch attributes that don't exist on the spec it doesn't prevent you setting them:
```
>>> with patch('__main__.Something', autospec=True):
... thing = Something()
... thing.a = 33
...
```
There is a more aggressive version of both *spec* and *autospec* that *does*prevent you setting non-existent attributes. This is useful if you want to ensure your code only *sets* valid attributes too, but obviously it prevents this particular scenario:
```
>>> with patch('__main__.Something', autospec=True, spec_set=True):
... thing = Something()
... thing.a = 33
...
Traceback (most recent call last):
...
AttributeError: Mock object has no attribute 'a'
```
Probably the best way of solving the problem is to add class attributes as default values for instance members initialised in [`__init__()`](../reference/datamodel.xhtml#object.__init__ "object.__init__"). Note that if you are only setting default attributes in [`__init__()`](../reference/datamodel.xhtml#object.__init__ "object.__init__") then providing them via class attributes (shared between instances of course) is faster too. e.g.
```
class Something:
a = 33
```
This brings up another issue. It is relatively common to provide a default value of `None` for members that will later be an object of a different type. `None` would be useless as a spec because it wouldn't let you access *any*attributes or methods on it. As `None` is *never* going to be useful as a spec, and probably indicates a member that will normally of some other type, autospec doesn't use a spec for members that are set to `None`. These will just be ordinary mocks (well - MagicMocks):
```
>>> class Something:
... member = None
...
>>> mock = create_autospec(Something)
>>> mock.member.foo.bar.baz()
<MagicMock name='mock.member.foo.bar.baz()' id='...'>
```
If modifying your production classes to add defaults isn't to your liking then there are more options. One of these is simply to use an instance as the spec rather than the class. The other is to create a subclass of the production class and add the defaults to the subclass without affecting the production class. Both of these require you to use an alternative object as the spec. Thankfully [`patch()`](#unittest.mock.patch "unittest.mock.patch") supports this - you can simply pass the alternative object as the *autospec* argument:
```
>>> class Something:
... def __init__(self):
... self.a = 33
...
>>> class SomethingForTest(Something):
... a = 33
...
>>> p = patch('__main__.Something', autospec=SomethingForTest)
>>> mock = p.start()
>>> mock.a
<NonCallableMagicMock name='Something.a' spec='int' id='...'>
```
[4](#id10)This only applies to classes or already instantiated objects. Calling a mocked class to create a mock instance *does not* create a real instance. It is only attribute lookups - along with calls to [`dir()`](functions.xhtml#dir "dir") - that are done.
### Sealing mocks
`unittest.mock.``seal`(*mock*)Seal will disable the automatic creation of mocks when accessing an attribute of the mock being sealed or any of its attributes that are already mocks recursively.
If a mock instance with a name or a spec is assigned to an attribute it won't be considered in the sealing chain. This allows one to prevent seal from fixing part of the mock object.
```
>>> mock = Mock()
>>> mock.submock.attribute1 = 2
>>> mock.not_submock = mock.Mock(name="sample_name")
>>> seal(mock)
>>> mock.new_attribute # This will raise AttributeError.
>>> mock.submock.attribute2 # This will raise AttributeError.
>>> mock.not_submock.attribute2 # This won't raise.
```
3\.7 新版功能.
### 导航
- [索引](../genindex.xhtml "总目录")
- [模块](../py-modindex.xhtml "Python 模块索引") |
- [下一页](unittest.mock-examples.xhtml "unittest.mock 上手指南") |
- [上一页](unittest.xhtml "unittest --- 单元测试框架") |
- ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png)
- [Python](https://www.python.org/) »
- zh\_CN 3.7.3 [文档](../index.xhtml) »
- [Python 标准库](index.xhtml) »
- [开发工具](development.xhtml) »
- $('.inline-search').show(0); |
© [版权所有](../copyright.xhtml) 2001-2019, Python Software Foundation.
Python 软件基金会是一个非盈利组织。 [请捐助。](https://www.python.org/psf/donations/)
最后更新于 5月 21, 2019. [发现了问题](../bugs.xhtml)?
使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 创建。
- Python文档内容
- Python 有什么新变化?
- Python 3.7 有什么新变化
- 摘要 - 发布重点
- 新的特性
- 其他语言特性修改
- 新增模块
- 改进的模块
- C API 的改变
- 构建的改变
- 性能优化
- 其他 CPython 实现的改变
- 已弃用的 Python 行为
- 已弃用的 Python 模块、函数和方法
- 已弃用的 C API 函数和类型
- 平台支持的移除
- API 与特性的移除
- 移除的模块
- Windows 专属的改变
- 移植到 Python 3.7
- Python 3.7.1 中的重要变化
- Python 3.7.2 中的重要变化
- Python 3.6 有什么新变化A
- 摘要 - 发布重点
- 新的特性
- 其他语言特性修改
- 新增模块
- 改进的模块
- 性能优化
- Build and C API Changes
- 其他改进
- 弃用
- 移除
- 移植到Python 3.6
- Python 3.6.2 中的重要变化
- Python 3.6.4 中的重要变化
- Python 3.6.5 中的重要变化
- Python 3.6.7 中的重要变化
- Python 3.5 有什么新变化
- 摘要 - 发布重点
- 新的特性
- 其他语言特性修改
- 新增模块
- 改进的模块
- Other module-level changes
- 性能优化
- Build and C API Changes
- 弃用
- 移除
- Porting to Python 3.5
- Notable changes in Python 3.5.4
- What's New In Python 3.4
- 摘要 - 发布重点
- 新的特性
- 新增模块
- 改进的模块
- CPython Implementation Changes
- 弃用
- 移除
- Porting to Python 3.4
- Changed in 3.4.3
- What's New In Python 3.3
- 摘要 - 发布重点
- PEP 405: Virtual Environments
- PEP 420: Implicit Namespace Packages
- PEP 3118: New memoryview implementation and buffer protocol documentation
- PEP 393: Flexible String Representation
- PEP 397: Python Launcher for Windows
- PEP 3151: Reworking the OS and IO exception hierarchy
- PEP 380: Syntax for Delegating to a Subgenerator
- PEP 409: Suppressing exception context
- PEP 414: Explicit Unicode literals
- PEP 3155: Qualified name for classes and functions
- PEP 412: Key-Sharing Dictionary
- PEP 362: Function Signature Object
- PEP 421: Adding sys.implementation
- Using importlib as the Implementation of Import
- 其他语言特性修改
- A Finer-Grained Import Lock
- Builtin functions and types
- 新增模块
- 改进的模块
- 性能优化
- Build and C API Changes
- 弃用
- Porting to Python 3.3
- What's New In Python 3.2
- PEP 384: Defining a Stable ABI
- PEP 389: Argparse Command Line Parsing Module
- PEP 391: Dictionary Based Configuration for Logging
- PEP 3148: The concurrent.futures module
- PEP 3147: PYC Repository Directories
- PEP 3149: ABI Version Tagged .so Files
- PEP 3333: Python Web Server Gateway Interface v1.0.1
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- 多线程
- 性能优化
- Unicode
- Codecs
- 文档
- IDLE
- Code Repository
- Build and C API Changes
- Porting to Python 3.2
- What's New In Python 3.1
- PEP 372: Ordered Dictionaries
- PEP 378: Format Specifier for Thousands Separator
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- 性能优化
- IDLE
- Build and C API Changes
- Porting to Python 3.1
- What's New In Python 3.0
- Common Stumbling Blocks
- Overview Of Syntax Changes
- Changes Already Present In Python 2.6
- Library Changes
- PEP 3101: A New Approach To String Formatting
- Changes To Exceptions
- Miscellaneous Other Changes
- Build and C API Changes
- 性能
- Porting To Python 3.0
- What's New in Python 2.7
- The Future for Python 2.x
- Changes to the Handling of Deprecation Warnings
- Python 3.1 Features
- PEP 372: Adding an Ordered Dictionary to collections
- PEP 378: Format Specifier for Thousands Separator
- PEP 389: The argparse Module for Parsing Command Lines
- PEP 391: Dictionary-Based Configuration For Logging
- PEP 3106: Dictionary Views
- PEP 3137: The memoryview Object
- 其他语言特性修改
- New and Improved Modules
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.7
- New Features Added to Python 2.7 Maintenance Releases
- Acknowledgements
- Python 2.6 有什么新变化
- Python 3.0
- Changes to the Development Process
- PEP 343: The 'with' statement
- PEP 366: Explicit Relative Imports From a Main Module
- PEP 370: Per-user site-packages Directory
- PEP 371: The multiprocessing Package
- PEP 3101: Advanced String Formatting
- PEP 3105: print As a Function
- PEP 3110: Exception-Handling Changes
- PEP 3112: Byte Literals
- PEP 3116: New I/O Library
- PEP 3118: Revised Buffer Protocol
- PEP 3119: Abstract Base Classes
- PEP 3127: Integer Literal Support and Syntax
- PEP 3129: Class Decorators
- PEP 3141: A Type Hierarchy for Numbers
- 其他语言特性修改
- New and Improved Modules
- Deprecations and Removals
- Build and C API Changes
- Porting to Python 2.6
- Acknowledgements
- What's New in Python 2.5
- PEP 308: Conditional Expressions
- PEP 309: Partial Function Application
- PEP 314: Metadata for Python Software Packages v1.1
- PEP 328: Absolute and Relative Imports
- PEP 338: Executing Modules as Scripts
- PEP 341: Unified try/except/finally
- PEP 342: New Generator Features
- PEP 343: The 'with' statement
- PEP 352: Exceptions as New-Style Classes
- PEP 353: Using ssize_t as the index type
- PEP 357: The 'index' method
- 其他语言特性修改
- New, Improved, and Removed Modules
- Build and C API Changes
- Porting to Python 2.5
- Acknowledgements
- What's New in Python 2.4
- PEP 218: Built-In Set Objects
- PEP 237: Unifying Long Integers and Integers
- PEP 289: Generator Expressions
- PEP 292: Simpler String Substitutions
- PEP 318: Decorators for Functions and Methods
- PEP 322: Reverse Iteration
- PEP 324: New subprocess Module
- PEP 327: Decimal Data Type
- PEP 328: Multi-line Imports
- PEP 331: Locale-Independent Float/String Conversions
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- Build and C API Changes
- Porting to Python 2.4
- Acknowledgements
- What's New in Python 2.3
- PEP 218: A Standard Set Datatype
- PEP 255: Simple Generators
- PEP 263: Source Code Encodings
- PEP 273: Importing Modules from ZIP Archives
- PEP 277: Unicode file name support for Windows NT
- PEP 278: Universal Newline Support
- PEP 279: enumerate()
- PEP 282: The logging Package
- PEP 285: A Boolean Type
- PEP 293: Codec Error Handling Callbacks
- PEP 301: Package Index and Metadata for Distutils
- PEP 302: New Import Hooks
- PEP 305: Comma-separated Files
- PEP 307: Pickle Enhancements
- Extended Slices
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- Pymalloc: A Specialized Object Allocator
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.3
- Acknowledgements
- What's New in Python 2.2
- 概述
- PEPs 252 and 253: Type and Class Changes
- PEP 234: Iterators
- PEP 255: Simple Generators
- PEP 237: Unifying Long Integers and Integers
- PEP 238: Changing the Division Operator
- Unicode Changes
- PEP 227: Nested Scopes
- New and Improved Modules
- Interpreter Changes and Fixes
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.1
- 概述
- PEP 227: Nested Scopes
- PEP 236: future Directives
- PEP 207: Rich Comparisons
- PEP 230: Warning Framework
- PEP 229: New Build System
- PEP 205: Weak References
- PEP 232: Function Attributes
- PEP 235: Importing Modules on Case-Insensitive Platforms
- PEP 217: Interactive Display Hook
- PEP 208: New Coercion Model
- PEP 241: Metadata in Python Packages
- New and Improved Modules
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.0
- 概述
- What About Python 1.6?
- New Development Process
- Unicode
- 列表推导式
- Augmented Assignment
- 字符串的方法
- Garbage Collection of Cycles
- Other Core Changes
- Porting to 2.0
- Extending/Embedding Changes
- Distutils: Making Modules Easy to Install
- XML Modules
- Module changes
- New modules
- IDLE Improvements
- Deleted and Deprecated Modules
- Acknowledgements
- 更新日志
- Python 下一版
- Python 3.7.3 最终版
- Python 3.7.3 发布候选版 1
- Python 3.7.2 最终版
- Python 3.7.2 发布候选版 1
- Python 3.7.1 最终版
- Python 3.7.1 RC 2版本
- Python 3.7.1 发布候选版 1
- Python 3.7.0 正式版
- Python 3.7.0 release candidate 1
- Python 3.7.0 beta 5
- Python 3.7.0 beta 4
- Python 3.7.0 beta 3
- Python 3.7.0 beta 2
- Python 3.7.0 beta 1
- Python 3.7.0 alpha 4
- Python 3.7.0 alpha 3
- Python 3.7.0 alpha 2
- Python 3.7.0 alpha 1
- Python 3.6.6 final
- Python 3.6.6 RC 1
- Python 3.6.5 final
- Python 3.6.5 release candidate 1
- Python 3.6.4 final
- Python 3.6.4 release candidate 1
- Python 3.6.3 final
- Python 3.6.3 release candidate 1
- Python 3.6.2 final
- Python 3.6.2 release candidate 2
- Python 3.6.2 release candidate 1
- Python 3.6.1 final
- Python 3.6.1 release candidate 1
- Python 3.6.0 final
- Python 3.6.0 release candidate 2
- Python 3.6.0 release candidate 1
- Python 3.6.0 beta 4
- Python 3.6.0 beta 3
- Python 3.6.0 beta 2
- Python 3.6.0 beta 1
- Python 3.6.0 alpha 4
- Python 3.6.0 alpha 3
- Python 3.6.0 alpha 2
- Python 3.6.0 alpha 1
- Python 3.5.5 final
- Python 3.5.5 release candidate 1
- Python 3.5.4 final
- Python 3.5.4 release candidate 1
- Python 3.5.3 final
- Python 3.5.3 release candidate 1
- Python 3.5.2 final
- Python 3.5.2 release candidate 1
- Python 3.5.1 final
- Python 3.5.1 release candidate 1
- Python 3.5.0 final
- Python 3.5.0 release candidate 4
- Python 3.5.0 release candidate 3
- Python 3.5.0 release candidate 2
- Python 3.5.0 release candidate 1
- Python 3.5.0 beta 4
- Python 3.5.0 beta 3
- Python 3.5.0 beta 2
- Python 3.5.0 beta 1
- Python 3.5.0 alpha 4
- Python 3.5.0 alpha 3
- Python 3.5.0 alpha 2
- Python 3.5.0 alpha 1
- Python 教程
- 课前甜点
- 使用 Python 解释器
- 调用解释器
- 解释器的运行环境
- Python 的非正式介绍
- Python 作为计算器使用
- 走向编程的第一步
- 其他流程控制工具
- if 语句
- for 语句
- range() 函数
- break 和 continue 语句,以及循环中的 else 子句
- pass 语句
- 定义函数
- 函数定义的更多形式
- 小插曲:编码风格
- 数据结构
- 列表的更多特性
- del 语句
- 元组和序列
- 集合
- 字典
- 循环的技巧
- 深入条件控制
- 序列和其它类型的比较
- 模块
- 有关模块的更多信息
- 标准模块
- dir() 函数
- 包
- 输入输出
- 更漂亮的输出格式
- 读写文件
- 错误和异常
- 语法错误
- 异常
- 处理异常
- 抛出异常
- 用户自定义异常
- 定义清理操作
- 预定义的清理操作
- 类
- 名称和对象
- Python 作用域和命名空间
- 初探类
- 补充说明
- 继承
- 私有变量
- 杂项说明
- 迭代器
- 生成器
- 生成器表达式
- 标准库简介
- 操作系统接口
- 文件通配符
- 命令行参数
- 错误输出重定向和程序终止
- 字符串模式匹配
- 数学
- 互联网访问
- 日期和时间
- 数据压缩
- 性能测量
- 质量控制
- 自带电池
- 标准库简介 —— 第二部分
- 格式化输出
- 模板
- 使用二进制数据记录格式
- 多线程
- 日志
- 弱引用
- 用于操作列表的工具
- 十进制浮点运算
- 虚拟环境和包
- 概述
- 创建虚拟环境
- 使用pip管理包
- 接下来?
- 交互式编辑和编辑历史
- Tab 补全和编辑历史
- 默认交互式解释器的替代品
- 浮点算术:争议和限制
- 表示性错误
- 附录
- 交互模式
- 安装和使用 Python
- 命令行与环境
- 命令行
- 环境变量
- 在Unix平台中使用Python
- 获取最新版本的Python
- 构建Python
- 与Python相关的路径和文件
- 杂项
- 编辑器和集成开发环境
- 在Windows上使用 Python
- 完整安装程序
- Microsoft Store包
- nuget.org 安装包
- 可嵌入的包
- 替代捆绑包
- 配置Python
- 适用于Windows的Python启动器
- 查找模块
- 附加模块
- 在Windows上编译Python
- 其他平台
- 在苹果系统上使用 Python
- 获取和安装 MacPython
- IDE
- 安装额外的 Python 包
- Mac 上的图形界面编程
- 在 Mac 上分发 Python 应用程序
- 其他资源
- Python 语言参考
- 概述
- 其他实现
- 标注
- 词法分析
- 行结构
- 其他形符
- 标识符和关键字
- 字面值
- 运算符
- 分隔符
- 数据模型
- 对象、值与类型
- 标准类型层级结构
- 特殊方法名称
- 协程
- 执行模型
- 程序的结构
- 命名与绑定
- 异常
- 导入系统
- importlib
- 包
- 搜索
- 加载
- 基于路径的查找器
- 替换标准导入系统
- Package Relative Imports
- 有关 main 的特殊事项
- 开放问题项
- 参考文献
- 表达式
- 算术转换
- 原子
- 原型
- await 表达式
- 幂运算符
- 一元算术和位运算
- 二元算术运算符
- 移位运算
- 二元位运算
- 比较运算
- 布尔运算
- 条件表达式
- lambda 表达式
- 表达式列表
- 求值顺序
- 运算符优先级
- 简单语句
- 表达式语句
- 赋值语句
- assert 语句
- pass 语句
- del 语句
- return 语句
- yield 语句
- raise 语句
- break 语句
- continue 语句
- import 语句
- global 语句
- nonlocal 语句
- 复合语句
- if 语句
- while 语句
- for 语句
- try 语句
- with 语句
- 函数定义
- 类定义
- 协程
- 最高层级组件
- 完整的 Python 程序
- 文件输入
- 交互式输入
- 表达式输入
- 完整的语法规范
- Python 标准库
- 概述
- 可用性注释
- 内置函数
- 内置常量
- 由 site 模块添加的常量
- 内置类型
- 逻辑值检测
- 布尔运算 — and, or, not
- 比较
- 数字类型 — int, float, complex
- 迭代器类型
- 序列类型 — list, tuple, range
- 文本序列类型 — str
- 二进制序列类型 — bytes, bytearray, memoryview
- 集合类型 — set, frozenset
- 映射类型 — dict
- 上下文管理器类型
- 其他内置类型
- 特殊属性
- 内置异常
- 基类
- 具体异常
- 警告
- 异常层次结构
- 文本处理服务
- string — 常见的字符串操作
- re — 正则表达式操作
- 模块 difflib 是一个计算差异的助手
- textwrap — Text wrapping and filling
- unicodedata — Unicode 数据库
- stringprep — Internet String Preparation
- readline — GNU readline interface
- rlcompleter — GNU readline的完成函数
- 二进制数据服务
- struct — Interpret bytes as packed binary data
- codecs — Codec registry and base classes
- 数据类型
- datetime — 基础日期/时间数据类型
- calendar — General calendar-related functions
- collections — 容器数据类型
- collections.abc — 容器的抽象基类
- heapq — 堆队列算法
- bisect — Array bisection algorithm
- array — Efficient arrays of numeric values
- weakref — 弱引用
- types — Dynamic type creation and names for built-in types
- copy — 浅层 (shallow) 和深层 (deep) 复制操作
- pprint — 数据美化输出
- reprlib — Alternate repr() implementation
- enum — Support for enumerations
- 数字和数学模块
- numbers — 数字的抽象基类
- math — 数学函数
- cmath — Mathematical functions for complex numbers
- decimal — 十进制定点和浮点运算
- fractions — 分数
- random — 生成伪随机数
- statistics — Mathematical statistics functions
- 函数式编程模块
- itertools — 为高效循环而创建迭代器的函数
- functools — 高阶函数和可调用对象上的操作
- operator — 标准运算符替代函数
- 文件和目录访问
- pathlib — 面向对象的文件系统路径
- os.path — 常见路径操作
- fileinput — Iterate over lines from multiple input streams
- stat — Interpreting stat() results
- filecmp — File and Directory Comparisons
- tempfile — Generate temporary files and directories
- glob — Unix style pathname pattern expansion
- fnmatch — Unix filename pattern matching
- linecache — Random access to text lines
- shutil — High-level file operations
- macpath — Mac OS 9 路径操作函数
- 数据持久化
- pickle —— Python 对象序列化
- copyreg — Register pickle support functions
- shelve — Python object persistence
- marshal — Internal Python object serialization
- dbm — Interfaces to Unix “databases”
- sqlite3 — SQLite 数据库 DB-API 2.0 接口模块
- 数据压缩和存档
- zlib — 与 gzip 兼容的压缩
- gzip — 对 gzip 格式的支持
- bz2 — 对 bzip2 压缩算法的支持
- lzma — 用 LZMA 算法压缩
- zipfile — 在 ZIP 归档中工作
- tarfile — Read and write tar archive files
- 文件格式
- csv — CSV 文件读写
- configparser — Configuration file parser
- netrc — netrc file processing
- xdrlib — Encode and decode XDR data
- plistlib — Generate and parse Mac OS X .plist files
- 加密服务
- hashlib — 安全哈希与消息摘要
- hmac — 基于密钥的消息验证
- secrets — Generate secure random numbers for managing secrets
- 通用操作系统服务
- os — 操作系统接口模块
- io — 处理流的核心工具
- time — 时间的访问和转换
- argparse — 命令行选项、参数和子命令解析器
- getopt — C-style parser for command line options
- 模块 logging — Python 的日志记录工具
- logging.config — 日志记录配置
- logging.handlers — Logging handlers
- getpass — 便携式密码输入工具
- curses — 终端字符单元显示的处理
- curses.textpad — Text input widget for curses programs
- curses.ascii — Utilities for ASCII characters
- curses.panel — A panel stack extension for curses
- platform — Access to underlying platform's identifying data
- errno — Standard errno system symbols
- ctypes — Python 的外部函数库
- 并发执行
- threading — 基于线程的并行
- multiprocessing — 基于进程的并行
- concurrent 包
- concurrent.futures — 启动并行任务
- subprocess — 子进程管理
- sched — 事件调度器
- queue — 一个同步的队列类
- _thread — 底层多线程 API
- _dummy_thread — _thread 的替代模块
- dummy_threading — 可直接替代 threading 模块。
- contextvars — Context Variables
- Context Variables
- Manual Context Management
- asyncio support
- 网络和进程间通信
- asyncio — 异步 I/O
- socket — 底层网络接口
- ssl — TLS/SSL wrapper for socket objects
- select — Waiting for I/O completion
- selectors — 高级 I/O 复用库
- asyncore — 异步socket处理器
- asynchat — 异步 socket 指令/响应 处理器
- signal — Set handlers for asynchronous events
- mmap — Memory-mapped file support
- 互联网数据处理
- email — 电子邮件与 MIME 处理包
- json — JSON 编码和解码器
- mailcap — Mailcap file handling
- mailbox — Manipulate mailboxes in various formats
- mimetypes — Map filenames to MIME types
- base64 — Base16, Base32, Base64, Base85 数据编码
- binhex — 对binhex4文件进行编码和解码
- binascii — 二进制和 ASCII 码互转
- quopri — Encode and decode MIME quoted-printable data
- uu — Encode and decode uuencode files
- 结构化标记处理工具
- html — 超文本标记语言支持
- html.parser — 简单的 HTML 和 XHTML 解析器
- html.entities — HTML 一般实体的定义
- XML处理模块
- xml.etree.ElementTree — The ElementTree XML API
- xml.dom — The Document Object Model API
- xml.dom.minidom — Minimal DOM implementation
- xml.dom.pulldom — Support for building partial DOM trees
- xml.sax — Support for SAX2 parsers
- xml.sax.handler — Base classes for SAX handlers
- xml.sax.saxutils — SAX Utilities
- xml.sax.xmlreader — Interface for XML parsers
- xml.parsers.expat — Fast XML parsing using Expat
- 互联网协议和支持
- webbrowser — 方便的Web浏览器控制器
- cgi — Common Gateway Interface support
- cgitb — Traceback manager for CGI scripts
- wsgiref — WSGI Utilities and Reference Implementation
- urllib — URL 处理模块
- urllib.request — 用于打开 URL 的可扩展库
- urllib.response — Response classes used by urllib
- urllib.parse — Parse URLs into components
- urllib.error — Exception classes raised by urllib.request
- urllib.robotparser — Parser for robots.txt
- http — HTTP 模块
- http.client — HTTP协议客户端
- ftplib — FTP protocol client
- poplib — POP3 protocol client
- imaplib — IMAP4 protocol client
- nntplib — NNTP protocol client
- smtplib —SMTP协议客户端
- smtpd — SMTP Server
- telnetlib — Telnet client
- uuid — UUID objects according to RFC 4122
- socketserver — A framework for network servers
- http.server — HTTP 服务器
- http.cookies — HTTP state management
- http.cookiejar — Cookie handling for HTTP clients
- xmlrpc — XMLRPC 服务端与客户端模块
- xmlrpc.client — XML-RPC client access
- xmlrpc.server — Basic XML-RPC servers
- ipaddress — IPv4/IPv6 manipulation library
- 多媒体服务
- audioop — Manipulate raw audio data
- aifc — Read and write AIFF and AIFC files
- sunau — 读写 Sun AU 文件
- wave — 读写WAV格式文件
- chunk — Read IFF chunked data
- colorsys — Conversions between color systems
- imghdr — 推测图像类型
- sndhdr — 推测声音文件的类型
- ossaudiodev — Access to OSS-compatible audio devices
- 国际化
- gettext — 多语种国际化服务
- locale — 国际化服务
- 程序框架
- turtle — 海龟绘图
- cmd — 支持面向行的命令解释器
- shlex — Simple lexical analysis
- Tk图形用户界面(GUI)
- tkinter — Tcl/Tk的Python接口
- tkinter.ttk — Tk themed widgets
- tkinter.tix — Extension widgets for Tk
- tkinter.scrolledtext — 滚动文字控件
- IDLE
- 其他图形用户界面(GUI)包
- 开发工具
- typing — 类型标注支持
- pydoc — Documentation generator and online help system
- doctest — Test interactive Python examples
- unittest — 单元测试框架
- unittest.mock — mock object library
- unittest.mock 上手指南
- 2to3 - 自动将 Python 2 代码转为 Python 3 代码
- test — Regression tests package for Python
- test.support — Utilities for the Python test suite
- test.support.script_helper — Utilities for the Python execution tests
- 调试和分析
- bdb — Debugger framework
- faulthandler — Dump the Python traceback
- pdb — The Python Debugger
- The Python Profilers
- timeit — 测量小代码片段的执行时间
- trace — Trace or track Python statement execution
- tracemalloc — Trace memory allocations
- 软件打包和分发
- distutils — 构建和安装 Python 模块
- ensurepip — Bootstrapping the pip installer
- venv — 创建虚拟环境
- zipapp — Manage executable Python zip archives
- Python运行时服务
- sys — 系统相关的参数和函数
- sysconfig — Provide access to Python's configuration information
- builtins — 内建对象
- main — 顶层脚本环境
- warnings — Warning control
- dataclasses — 数据类
- contextlib — Utilities for with-statement contexts
- abc — 抽象基类
- atexit — 退出处理器
- traceback — Print or retrieve a stack traceback
- future — Future 语句定义
- gc — 垃圾回收器接口
- inspect — 检查对象
- site — Site-specific configuration hook
- 自定义 Python 解释器
- code — Interpreter base classes
- codeop — Compile Python code
- 导入模块
- zipimport — Import modules from Zip archives
- pkgutil — Package extension utility
- modulefinder — 查找脚本使用的模块
- runpy — Locating and executing Python modules
- importlib — The implementation of import
- Python 语言服务
- parser — Access Python parse trees
- ast — 抽象语法树
- symtable — Access to the compiler's symbol tables
- symbol — 与 Python 解析树一起使用的常量
- token — 与Python解析树一起使用的常量
- keyword — 检验Python关键字
- tokenize — Tokenizer for Python source
- tabnanny — 模糊缩进检测
- pyclbr — Python class browser support
- py_compile — Compile Python source files
- compileall — Byte-compile Python libraries
- dis — Python 字节码反汇编器
- pickletools — Tools for pickle developers
- 杂项服务
- formatter — Generic output formatting
- Windows系统相关模块
- msilib — Read and write Microsoft Installer files
- msvcrt — Useful routines from the MS VC++ runtime
- winreg — Windows 注册表访问
- winsound — Sound-playing interface for Windows
- Unix 专有服务
- posix — The most common POSIX system calls
- pwd — 用户密码数据库
- spwd — The shadow password database
- grp — The group database
- crypt — Function to check Unix passwords
- termios — POSIX style tty control
- tty — 终端控制功能
- pty — Pseudo-terminal utilities
- fcntl — The fcntl and ioctl system calls
- pipes — Interface to shell pipelines
- resource — Resource usage information
- nis — Interface to Sun's NIS (Yellow Pages)
- Unix syslog 库例程
- 被取代的模块
- optparse — Parser for command line options
- imp — Access the import internals
- 未创建文档的模块
- 平台特定模块
- 扩展和嵌入 Python 解释器
- 推荐的第三方工具
- 不使用第三方工具创建扩展
- 使用 C 或 C++ 扩展 Python
- 自定义扩展类型:教程
- 定义扩展类型:已分类主题
- 构建C/C++扩展
- 在Windows平台编译C和C++扩展
- 在更大的应用程序中嵌入 CPython 运行时
- Embedding Python in Another Application
- Python/C API 参考手册
- 概述
- 代码标准
- 包含文件
- 有用的宏
- 对象、类型和引用计数
- 异常
- 嵌入Python
- 调试构建
- 稳定的应用程序二进制接口
- The Very High Level Layer
- Reference Counting
- 异常处理
- Printing and clearing
- 抛出异常
- Issuing warnings
- Querying the error indicator
- Signal Handling
- Exception Classes
- Exception Objects
- Unicode Exception Objects
- Recursion Control
- 标准异常
- 标准警告类别
- 工具
- 操作系统实用程序
- 系统功能
- 过程控制
- 导入模块
- Data marshalling support
- 语句解释及变量编译
- 字符串转换与格式化
- 反射
- 编解码器注册与支持功能
- 抽象对象层
- Object Protocol
- 数字协议
- Sequence Protocol
- Mapping Protocol
- 迭代器协议
- 缓冲协议
- Old Buffer Protocol
- 具体的对象层
- 基本对象
- 数值对象
- 序列对象
- 容器对象
- 函数对象
- 其他对象
- Initialization, Finalization, and Threads
- 在Python初始化之前
- 全局配置变量
- Initializing and finalizing the interpreter
- Process-wide parameters
- Thread State and the Global Interpreter Lock
- Sub-interpreter support
- Asynchronous Notifications
- Profiling and Tracing
- Advanced Debugger Support
- Thread Local Storage Support
- 内存管理
- 概述
- 原始内存接口
- Memory Interface
- 对象分配器
- 默认内存分配器
- Customize Memory Allocators
- The pymalloc allocator
- tracemalloc C API
- 示例
- 对象实现支持
- 在堆中分配对象
- Common Object Structures
- Type 对象
- Number Object Structures
- Mapping Object Structures
- Sequence Object Structures
- Buffer Object Structures
- Async Object Structures
- 使对象类型支持循环垃圾回收
- API 和 ABI 版本管理
- 分发 Python 模块
- 关键术语
- 开源许可与协作
- 安装工具
- 阅读指南
- 我该如何...?
- ...为我的项目选择一个名字?
- ...创建和分发二进制扩展?
- 安装 Python 模块
- 关键术语
- 基本使用
- 我应如何 ...?
- ... 在 Python 3.4 之前的 Python 版本中安装 pip ?
- ... 只为当前用户安装软件包?
- ... 安装科学计算类 Python 软件包?
- ... 使用并行安装的多个 Python 版本?
- 常见的安装问题
- 在 Linux 的系统 Python 版本上安装
- 未安装 pip
- 安装二进制编译扩展
- Python 常用指引
- 将 Python 2 代码迁移到 Python 3
- 简要说明
- 详情
- 将扩展模块移植到 Python 3
- 条件编译
- 对象API的更改
- 模块初始化和状态
- CObject 替换为 Capsule
- 其他选项
- Curses Programming with Python
- What is curses?
- Starting and ending a curses application
- Windows and Pads
- Displaying Text
- User Input
- For More Information
- 实现描述器
- 摘要
- 定义和简介
- 描述器协议
- 发起调用描述符
- 描述符示例
- Properties
- 函数和方法
- Static Methods and Class Methods
- 函数式编程指引
- 概述
- 迭代器
- 生成器表达式和列表推导式
- 生成器
- 内置函数
- itertools 模块
- The functools module
- Small functions and the lambda expression
- Revision History and Acknowledgements
- 引用文献
- 日志 HOWTO
- 日志基础教程
- 进阶日志教程
- 日志级别
- 有用的处理程序
- 记录日志中引发的异常
- 使用任意对象作为消息
- 优化
- 日志操作手册
- 在多个模块中使用日志
- 在多线程中使用日志
- 使用多个日志处理器和多种格式化
- 在多个地方记录日志
- 日志服务器配置示例
- 处理日志处理器的阻塞
- Sending and receiving logging events across a network
- Adding contextual information to your logging output
- Logging to a single file from multiple processes
- Using file rotation
- Use of alternative formatting styles
- Customizing LogRecord
- Subclassing QueueHandler - a ZeroMQ example
- Subclassing QueueListener - a ZeroMQ example
- An example dictionary-based configuration
- Using a rotator and namer to customize log rotation processing
- A more elaborate multiprocessing example
- Inserting a BOM into messages sent to a SysLogHandler
- Implementing structured logging
- Customizing handlers with dictConfig()
- Using particular formatting styles throughout your application
- Configuring filters with dictConfig()
- Customized exception formatting
- Speaking logging messages
- Buffering logging messages and outputting them conditionally
- Formatting times using UTC (GMT) via configuration
- Using a context manager for selective logging
- 正则表达式HOWTO
- 概述
- 简单模式
- 使用正则表达式
- 更多模式能力
- 修改字符串
- 常见问题
- 反馈
- 套接字编程指南
- 套接字
- 创建套接字
- 使用一个套接字
- 断开连接
- 非阻塞的套接字
- 排序指南
- 基本排序
- 关键函数
- Operator 模块函数
- 升序和降序
- 排序稳定性和排序复杂度
- 使用装饰-排序-去装饰的旧方法
- 使用 cmp 参数的旧方法
- 其它
- Unicode 指南
- Unicode 概述
- Python's Unicode Support
- Reading and Writing Unicode Data
- Acknowledgements
- 如何使用urllib包获取网络资源
- 概述
- Fetching URLs
- 处理异常
- info and geturl
- Openers and Handlers
- Basic Authentication
- Proxies
- Sockets and Layers
- 脚注
- Argparse 教程
- 概念
- 基础
- 位置参数介绍
- Introducing Optional arguments
- Combining Positional and Optional arguments
- Getting a little more advanced
- Conclusion
- ipaddress模块介绍
- 创建 Address/Network/Interface 对象
- 审查 Address/Network/Interface 对象
- Network 作为 Address 列表
- 比较
- 将IP地址与其他模块一起使用
- 实例创建失败时获取更多详细信息
- Argument Clinic How-To
- The Goals Of Argument Clinic
- Basic Concepts And Usage
- Converting Your First Function
- Advanced Topics
- 使用 DTrace 和 SystemTap 检测CPython
- Enabling the static markers
- Static DTrace probes
- Static SystemTap markers
- Available static markers
- SystemTap Tapsets
- 示例
- Python 常见问题
- Python常见问题
- 一般信息
- 现实世界中的 Python
- 编程常见问题
- 一般问题
- 核心语言
- 数字和字符串
- 性能
- 序列(元组/列表)
- 对象
- 模块
- 设计和历史常见问题
- 为什么Python使用缩进来分组语句?
- 为什么简单的算术运算得到奇怪的结果?
- 为什么浮点计算不准确?
- 为什么Python字符串是不可变的?
- 为什么必须在方法定义和调用中显式使用“self”?
- 为什么不能在表达式中赋值?
- 为什么Python对某些功能(例如list.index())使用方法来实现,而其他功能(例如len(List))使用函数实现?
- 为什么 join()是一个字符串方法而不是列表或元组方法?
- 异常有多快?
- 为什么Python中没有switch或case语句?
- 难道不能在解释器中模拟线程,而非得依赖特定于操作系统的线程实现吗?
- 为什么lambda表达式不能包含语句?
- 可以将Python编译为机器代码,C或其他语言吗?
- Python如何管理内存?
- 为什么CPython不使用更传统的垃圾回收方案?
- CPython退出时为什么不释放所有内存?
- 为什么有单独的元组和列表数据类型?
- 列表是如何在CPython中实现的?
- 字典是如何在CPython中实现的?
- 为什么字典key必须是不可变的?
- 为什么 list.sort() 没有返回排序列表?
- 如何在Python中指定和实施接口规范?
- 为什么没有goto?
- 为什么原始字符串(r-strings)不能以反斜杠结尾?
- 为什么Python没有属性赋值的“with”语句?
- 为什么 if/while/def/class语句需要冒号?
- 为什么Python在列表和元组的末尾允许使用逗号?
- 代码库和插件 FAQ
- 通用的代码库问题
- 通用任务
- 线程相关
- 输入输出
- 网络 / Internet 编程
- 数据库
- 数学和数字
- 扩展/嵌入常见问题
- 可以使用C语言中创建自己的函数吗?
- 可以使用C++语言中创建自己的函数吗?
- C很难写,有没有其他选择?
- 如何从C执行任意Python语句?
- 如何从C中评估任意Python表达式?
- 如何从Python对象中提取C的值?
- 如何使用Py_BuildValue()创建任意长度的元组?
- 如何从C调用对象的方法?
- 如何捕获PyErr_Print()(或打印到stdout / stderr的任何内容)的输出?
- 如何从C访问用Python编写的模块?
- 如何从Python接口到C ++对象?
- 我使用Setup文件添加了一个模块,为什么make失败了?
- 如何调试扩展?
- 我想在Linux系统上编译一个Python模块,但是缺少一些文件。为什么?
- 如何区分“输入不完整”和“输入无效”?
- 如何找到未定义的g++符号__builtin_new或__pure_virtual?
- 能否创建一个对象类,其中部分方法在C中实现,而其他方法在Python中实现(例如通过继承)?
- Python在Windows上的常见问题
- 我怎样在Windows下运行一个Python程序?
- 我怎么让 Python 脚本可执行?
- 为什么有时候 Python 程序会启动缓慢?
- 我怎样使用Python脚本制作可执行文件?
- *.pyd 文件和DLL文件相同吗?
- 我怎样将Python嵌入一个Windows程序?
- 如何让编辑器不要在我的 Python 源代码中插入 tab ?
- 如何在不阻塞的情况下检查按键?
- 图形用户界面(GUI)常见问题
- 图形界面常见问题
- Python 是否有平台无关的图形界面工具包?
- 有哪些Python的GUI工具是某个平台专用的?
- 有关Tkinter的问题
- “为什么我的电脑上安装了 Python ?”
- 什么是Python?
- 为什么我的电脑上安装了 Python ?
- 我能删除 Python 吗?
- 术语对照表
- 文档说明
- Python 文档贡献者
- 解决 Bug
- 文档错误
- 使用 Python 的错误追踪系统
- 开始为 Python 贡献您的知识
- 版权
- 历史和许可证
- 软件历史
- 访问Python或以其他方式使用Python的条款和条件
- Python 3.7.3 的 PSF 许可协议
- Python 2.0 的 BeOpen.com 许可协议
- Python 1.6.1 的 CNRI 许可协议
- Python 0.9.0 至 1.2 的 CWI 许可协议
- 集成软件的许可和认可
- Mersenne Twister
- 套接字
- Asynchronous socket services
- Cookie management
- Execution tracing
- UUencode and UUdecode functions
- XML Remote Procedure Calls
- test_epoll
- Select kqueue
- SipHash24
- strtod and dtoa
- OpenSSL
- expat
- libffi
- zlib
- cfuhash
- libmpdec