Skip to content

Commit 41cb0ba

Browse files
authored
bpo-33985: Implement ContextVar.name attribute. (GH-7980)
1 parent 9b9d58f commit 41cb0ba

File tree

4 files changed

+15
-2
lines changed

4 files changed

+15
-2
lines changed

Doc/library/contextvars.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ Context Variables
4848

4949
The name of the variable. This is a read-only property.
5050

51+
.. versionadded:: 3.7.1
52+
5153
.. method:: get([default])
5254

5355
Return a value for the context variable for the current context.

Lib/test/test_context.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,13 @@ def test_context_var_new_1(self):
3030
with self.assertRaisesRegex(TypeError, 'must be a str'):
3131
contextvars.ContextVar(1)
3232

33-
c = contextvars.ContextVar('a')
34-
self.assertNotEqual(hash(c), hash('a'))
33+
c = contextvars.ContextVar('aaa')
34+
self.assertEqual(c.name, 'aaa')
35+
36+
with self.assertRaises(AttributeError):
37+
c.name = 'bbb'
38+
39+
self.assertNotEqual(hash(c), hash('aaa'))
3540

3641
def test_context_var_new_2(self):
3742
self.assertIsNone(contextvars.ContextVar[int])
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Implement contextvars.ContextVar.name attribute.

Python/context.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -940,6 +940,10 @@ contextvar_cls_getitem(PyObject *self, PyObject *args)
940940
Py_RETURN_NONE;
941941
}
942942

943+
static PyMemberDef PyContextVar_members[] = {
944+
{"name", T_OBJECT, offsetof(PyContextVar, var_name), READONLY},
945+
{NULL}
946+
};
943947

944948
static PyMethodDef PyContextVar_methods[] = {
945949
_CONTEXTVARS_CONTEXTVAR_GET_METHODDEF
@@ -955,6 +959,7 @@ PyTypeObject PyContextVar_Type = {
955959
"ContextVar",
956960
sizeof(PyContextVar),
957961
.tp_methods = PyContextVar_methods,
962+
.tp_members = PyContextVar_members,
958963
.tp_dealloc = (destructor)contextvar_tp_dealloc,
959964
.tp_getattro = PyObject_GenericGetAttr,
960965
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,

0 commit comments

Comments
 (0)