Skip to content

Commit 5e4d05f

Browse files
committed
add test for PyFunction_GetAnnotations function
1 parent b22ff1e commit 5e4d05f

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

Lib/test/test_capi/test_function.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -307,10 +307,27 @@ def function_without_closure(): ...
307307
_testcapi.function_get_closure(function_without_closure), (1, 2))
308308
self.assertEqual(function_without_closure.__closure__, (1, 2))
309309

310+
def test_function_get_annotations(self):
311+
# Test PyFunction_GetAnnotations()
312+
def normal():
313+
pass
314+
315+
def annofn(arg: int) -> str:
316+
return f'arg = {arg}'
317+
318+
annotations = _testcapi.function_get_annotations(normal)
319+
self.assertIsNone(annotations)
320+
321+
annotations = _testcapi.function_get_annotations(annofn)
322+
self.assertIsInstance(annotations, dict)
323+
self.assertEqual(annotations, annofn.__annotations__)
324+
325+
with self.assertRaises(SystemError):
326+
_testcapi.function_get_annotations(None)
327+
310328
# TODO: test PyFunction_New()
311329
# TODO: test PyFunction_NewWithQualName()
312330
# TODO: test PyFunction_SetVectorcall()
313-
# TODO: test PyFunction_GetAnnotations()
314331
# TODO: test PyFunction_SetAnnotations()
315332
# TODO: test PyClassMethod_New()
316333
# TODO: test PyStaticMethod_New()

Modules/_testcapi/function.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,18 @@ function_set_closure(PyObject *self, PyObject *args)
123123
}
124124

125125

126+
static PyObject *
127+
function_get_annotations(PyObject *self, PyObject *func)
128+
{
129+
PyObject *annotations = PyFunction_GetAnnotations(func);
130+
if (annotations != NULL) {
131+
return Py_NewRef(annotations);
132+
} else {
133+
return NULL;
134+
}
135+
}
136+
137+
126138
static PyMethodDef test_methods[] = {
127139
{"function_get_code", function_get_code, METH_O, NULL},
128140
{"function_get_globals", function_get_globals, METH_O, NULL},
@@ -133,6 +145,7 @@ static PyMethodDef test_methods[] = {
133145
{"function_set_kw_defaults", function_set_kw_defaults, METH_VARARGS, NULL},
134146
{"function_get_closure", function_get_closure, METH_O, NULL},
135147
{"function_set_closure", function_set_closure, METH_VARARGS, NULL},
148+
{"function_get_annotations", function_get_annotations, METH_O, NULL},
136149
{NULL},
137150
};
138151

0 commit comments

Comments
 (0)