### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](unittest.mock-examples.xhtml "unittest.mock 上手指南") |
- [上一頁](unittest.xhtml "unittest --- 單元測試框架") |
- 
- [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 --- 單元測試框架") |
- 
- [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