16. Context Managers¶
This chapter describes how to write for your C objects.
16.1. C Functions¶
This is a summary of what is required for the C functions implementing a context manger.
The is no specific tp_... slot for the context manager functions __enter__ and __exit__, instead they are added
to the object as named, looked up, Python methods.
16.1.1. __enter__¶
The C function must, at least, increment the reference count of self and
return self:
static PyObject *
ContextManager_enter(ContextManager *self, PyObject *Py_UNUSED(args)) {
/* Stuff here. */
Py_INCREF(self);
return (PyObject *)self;
}
16.1.2. __exit__¶
The __exit__() function is declared thus.
It takes three arguments so METH_VARARGS is used.
The three arguments are each None if no exception has been raised within
the with block.
If an exception has been raised within the with block then the
three arguments are the exception type, value and the traceback object.
The return value of the __exit__ method tells the interpreter whether
any exception should be suppressed.
If the function returns False then the exception should be
propagated.
This is the common case.
If the function returns True then the exception should be
suppressed and execution continues with the statement immediately
after the with statement.
The exit method is defined in C thus. Note that there is no change to the reference count, that is all done appropriately by the CPython interpreter:
static PyObject *
ContextManager_exit(ContextManager *self, PyObject *args) {
/* Stuff. */
Py_RETURN_FALSE;
}
16.1.3. Method declarations¶
Note that __enter__() is declared with METH_NOARGS and __exit__() is declared with METH_VARARGS:
static PyMethodDef ContextManager_methods[] = {
/* ... */
{"__enter__", (PyCFunction) ContextManager_enter, METH_NOARGS,
PyDoc_STR("__enter__() -> ContextManager")},
{"__exit__", (PyCFunction) ContextManager_exit, METH_VARARGS,
PyDoc_STR("__exit__(exc_type, exc_value, exc_tb) -> bool")},
/* ... */
{NULL, NULL, 0, NULL} /* sentinel */
};
16.2. Understanding the Context Manager¶
What is worth understanding is the way that reference counts are incremented and decremented and the interplay between your C code and the CPython interpreter.
16.2.1. A Context Manager Without a Target¶
Take this simple code:
from cPyExtPatt import cCtxMgr
with cCtxMgr.ContextManager():
pass
The sequence of reference count changes are as follows:
Creating the
cCtxMgr.ContextManager()callsContextManager_newwhich makes the reference count 1.The
withstatement causes the CPython interpreter to increment the reference count (to 2) and then call__enter__that is implemented in our C functionContextManager_enter.Our
ContextManager_enterfunction increments the reference count, so it is now 3.As the context manager ends the
withstatement the CPython interpreter decrements the reference count twice to the value 1. The logic is:Decrement the reference count once as we are exiting the
withstatement. The reference count is now 2.Did the
withstatement have a target? If not, as in this case, then decrement the reference count once more. The reference count is now 1.
after the
passstatement the CPython interpreter then calls__exit__which is implemented in our functionContextManager_exit. This does not change the reference count which remains at 1.As the context manager goes out of scope the CPython interpreter decrements the reference count to 0 and then calls our C function
ContextManager_deallocwith a reference count of 0 and that frees the object.
16.2.2. A Context Manager With a Target¶
The importance of the with statement having a target is because a context manager
can be used like this:
from cPyExtPatt import cCtxMgr
with cCtxMgr.ContextManager() as context:
pass
# context survives here with a reference count of 1.
# This will be decremented when context goes out of scope.
# For example on a function return.
In this case the context survives the with statement and is available to any following code.
So step 4 above would only decrement the reference count once leaving it with a reference count of 2.
The context variable reference count will be finally decremented when it goes out of scope, for
example on a function return.
The sequence of reference count changes are now as follows:
As above, the reference count becomes 1.
As above, the reference count becomes 2.
As above, the reference count becomes 3.
As the context manager ends the
withstatement the CPython interpreter decrements the reference count just once to the value 2 as there is a target, calledcontextin this case.After the
passstatement the CPython interpreter then calls__exit__which is implemented in our functionContextManager_exit. This does not change the reference count which remains at 2.As the context manager goes out of scope the CPython interpreter decrements the reference count to 1. This ensures the survival of
contextafter thewithblock.When
contextgoes out of scope, say on a function return or adelstatement the CPython interpreter decrements the reference count to 0 and then calls our C functionContextManager_deallocwhich frees the object.
16.3. Minimal Context Manager in C¶
Here is the minimal, complete, C code that implements context manager.
There is example code in src/cpy/CtxMgr/cCtxMgr.c and tests in
tests/unit/test_c_ctxmgr.py
First the object declaration, allocation and de-allocation functions:
1#define PY_SSIZE_T_CLEAN
2
3#include "Python.h"
4
5typedef struct {
6 PyObject_HEAD
7} ContextManager;
8
9static ContextManager *
10ContextManager_new(PyObject *Py_UNUSED(arg)) {
11 return PyObject_New(ContextManager, &ContextManager_Type);;
12}
13
14static void
15ContextManager_dealloc(ContextManager *self) {
16 PyObject_Del(self);
17}
16.3.1. __enter__ and __exit__ Methods¶
The __enter__ and __exit__ methods:
1static PyObject *
2ContextManager_enter(ContextManager *self, PyObject *Py_UNUSED(args)) {
3 Py_INCREF(self);
4 return (PyObject *)self;
5}
6
7static PyObject *
8ContextManager_exit(ContextManager *Py_UNUSED(self), PyObject *Py_UNUSED(args)) {
9 Py_RETURN_FALSE;
10}
11
12static PyMethodDef ContextManager_methods[] = {
13 {"__enter__", (PyCFunction) ContextManager_enter, METH_VARARGS,
14 PyDoc_STR("__enter__() -> ContextManager")},
15 {"__exit__", (PyCFunction) ContextManager_exit, METH_VARARGS,
16 PyDoc_STR("__exit__() -> bool")},
17 {NULL, NULL, 0, NULL} /* sentinel */
18};
16.3.2. Type Declaration¶
The type declaration:
static PyTypeObject ContextManager_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "cObject.ContextManager",
.tp_basicsize = sizeof(ContextManager),
.tp_dealloc = (destructor) ContextManager_dealloc,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_methods = ContextManager_methods,
.tp_new = (newfunc) ContextManager_new,
};
16.3.3. Module¶
Finally the module:
1PyDoc_STRVAR(module_doc, "Example of a context manager.");
2
3static struct PyModuleDef cCtxMgr = {
4 PyModuleDef_HEAD_INIT,
5 .m_name = "cCtxMgr",
6 .m_doc = module_doc,
7 .m_size = -1,
8};
9
10PyMODINIT_FUNC
11PyInit_cCtxMgr(void) {
12 PyObject *m = NULL;
13 m = PyModule_Create(&cCtxMgr);
14 if (m == NULL) {
15 goto fail;
16 }
17 if (PyType_Ready(&ContextManager_Type) < 0) {
18 goto fail;
19 }
20 if (PyModule_AddObject(m, "ContextManager", (PyObject *) &ContextManager_Type)) {
21 goto fail;
22 }
23 return m;
24fail:
25 Py_XDECREF(m);
26 return NULL;
27}
16.3.4. Setup¶
This code is added to the setup.py file:
Extension(f"{PACKAGE_NAME}.cCtxMgr", sources=['src/cpy/CtxMgr/cCtxMgr.c', ],
include_dirs=['/usr/local/include', ],
library_dirs=[os.getcwd(), ],
extra_compile_args=extra_compile_args_c,
language='c',
),
And can be used thus:
from cPyExtPatt import cCtxMgr
with cCtxMgr.ContextManager():
pass
16.3.5. Testing¶
The actual code in src/cpy/CtxMgr/cCtxMgr.c contains extra trace reporting that confirms the reference counts and
(no) memory leakage.
This can be run with:
$ pytest tests/unit/test_c_ctxmgr.py -vs
This test:
def test_very_simple():
print()
with cCtxMgr.ContextManager():
pass
Gives this output:
tests/unit/test_c_ctxmgr.py::test_very_simple
ContextManager_new DONE REFCNT = 1
ContextManager_enter STRT REFCNT = 2
ContextManager_enter DONE REFCNT = 3
ContextManager_exit STRT REFCNT = 1
ContextManager_exit DONE REFCNT = 1
ContextManager_dealloc STRT REFCNT = 0
ContextManager_dealloc DONE REFCNT = 4546088432
This test:
1def test_simple():
2 print()
3 with cCtxMgr.ContextManager() as context:
4 assert sys.getrefcount(context) == 3
5 assert context.len_buffer_lifetime() == cCtxMgr.BUFFER_LENGTH
6 assert context.len_buffer_context() == cCtxMgr.BUFFER_LENGTH
7 assert sys.getrefcount(context) == 2
8 assert context.len_buffer_lifetime() == cCtxMgr.BUFFER_LENGTH
9 assert context.len_buffer_context() == 0
10 del context
Gives this output:
tests/unit/test_c_ctxmgr.py::test_simple
ContextManager_new DONE REFCNT = 1
ContextManager_enter STRT REFCNT = 2
ContextManager_enter DONE REFCNT = 3
ContextManager_exit STRT REFCNT = 2
ContextManager_exit DONE REFCNT = 2
ContextManager_dealloc STRT REFCNT = 0
ContextManager_dealloc DONE REFCNT = 4546096048
This test:
1def test_memory():
2 proc = psutil.Process()
3 print()
4 print(f'RSS START: {proc.memory_info().rss:12,d}')
5 for i in range(8):
6 print(f'RSS START {i:5d}: {proc.memory_info().rss:12,d}')
7 with cCtxMgr.ContextManager() as context:
8 print(f'RSS START CTX: {proc.memory_info().rss:12,d}')
9 # Does not work in the debugger due to introspection.
10 # assert sys.getrefcount(context) == 3
11 assert context.len_buffer_lifetime() == cCtxMgr.BUFFER_LENGTH
12 assert context.len_buffer_context() == cCtxMgr.BUFFER_LENGTH
13 print(f'RSS END CTX: {proc.memory_info().rss:12,d}')
14 # Does not work in the debugger due to introspection.
15 # assert sys.getrefcount(context) == 2
16 assert context.len_buffer_lifetime() == cCtxMgr.BUFFER_LENGTH
17 assert context.len_buffer_context() == 0
18 del context
19 print(f'RSS END {i:5d}: {proc.memory_info().rss:12,d}')
20 print(f'RSS END: {proc.memory_info().rss:12,d}')
Gives this output:
1tests/unit/test_c_ctxmgr.py::test_memory
2RSS START: 300,032,000
3RSS START 0: 300,048,384
4 ContextManager_new DONE REFCNT = 1
5 ContextManager_enter STRT REFCNT = 2
6 ContextManager_enter DONE REFCNT = 3
7RSS START CTX: 300,048,384
8RSS END CTX: 300,048,384
9 ContextManager_exit STRT REFCNT = 2
10 ContextManager_exit DONE REFCNT = 2
11 ContextManager_dealloc STRT REFCNT = 0
12 ContextManager_dealloc DONE REFCNT = 4546096048
13RSS END 0: 300,048,384
14RSS START 1: 300,048,384
15 ContextManager_new DONE REFCNT = 1
16 ContextManager_enter STRT REFCNT = 2
17 ContextManager_enter DONE REFCNT = 3
18RSS START CTX: 300,048,384
19RSS END CTX: 300,048,384
20 ContextManager_exit STRT REFCNT = 2
21 ContextManager_exit DONE REFCNT = 2
22 ContextManager_dealloc STRT REFCNT = 0
23 ContextManager_dealloc DONE REFCNT = 4546096048
24RSS END 1: 300,048,384
25RSS START 2: 300,048,384
26 ContextManager_new DONE REFCNT = 1
27 ContextManager_enter STRT REFCNT = 2
28 ContextManager_enter DONE REFCNT = 3
29RSS START CTX: 300,048,384
30RSS END CTX: 300,048,384
31 ContextManager_exit STRT REFCNT = 2
32 ContextManager_exit DONE REFCNT = 2
33 ContextManager_dealloc STRT REFCNT = 0
34 ContextManager_dealloc DONE REFCNT = 4546096048
35RSS END 2: 300,048,384
36RSS START 3: 300,048,384
37 ContextManager_new DONE REFCNT = 1
38 ContextManager_enter STRT REFCNT = 2
39 ContextManager_enter DONE REFCNT = 3
40RSS START CTX: 300,048,384
41RSS END CTX: 300,048,384
42 ContextManager_exit STRT REFCNT = 2
43 ContextManager_exit DONE REFCNT = 2
44 ContextManager_dealloc STRT REFCNT = 0
45 ContextManager_dealloc DONE REFCNT = 4546096048
46RSS END 3: 300,048,384
47RSS START 4: 300,048,384
48 ContextManager_new DONE REFCNT = 1
49 ContextManager_enter STRT REFCNT = 2
50 ContextManager_enter DONE REFCNT = 3
51RSS START CTX: 300,048,384
52RSS END CTX: 300,048,384
53 ContextManager_exit STRT REFCNT = 2
54 ContextManager_exit DONE REFCNT = 2
55 ContextManager_dealloc STRT REFCNT = 0
56 ContextManager_dealloc DONE REFCNT = 4546096048
57RSS END 4: 300,048,384
58RSS START 5: 300,048,384
59 ContextManager_new DONE REFCNT = 1
60 ContextManager_enter STRT REFCNT = 2
61 ContextManager_enter DONE REFCNT = 3
62RSS START CTX: 300,048,384
63RSS END CTX: 300,048,384
64 ContextManager_exit STRT REFCNT = 2
65 ContextManager_exit DONE REFCNT = 2
66 ContextManager_dealloc STRT REFCNT = 0
67 ContextManager_dealloc DONE REFCNT = 4546096048
68RSS END 5: 300,048,384
69RSS START 6: 300,048,384
70 ContextManager_new DONE REFCNT = 1
71 ContextManager_enter STRT REFCNT = 2
72 ContextManager_enter DONE REFCNT = 3
73RSS START CTX: 300,048,384
74RSS END CTX: 300,048,384
75 ContextManager_exit STRT REFCNT = 2
76 ContextManager_exit DONE REFCNT = 2
77 ContextManager_dealloc STRT REFCNT = 0
78 ContextManager_dealloc DONE REFCNT = 4546096048
79RSS END 6: 300,048,384
80RSS START 7: 300,048,384
81 ContextManager_new DONE REFCNT = 1
82 ContextManager_enter STRT REFCNT = 2
83 ContextManager_enter DONE REFCNT = 3
84RSS START CTX: 300,048,384
85RSS END CTX: 300,048,384
86 ContextManager_exit STRT REFCNT = 2
87 ContextManager_exit DONE REFCNT = 2
88 ContextManager_dealloc STRT REFCNT = 0
89 ContextManager_dealloc DONE REFCNT = 4546096048
90RSS END 7: 300,048,384
91RSS END: 300,048,384