Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion Lib/test/test_capi/test_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,10 +307,27 @@ def function_without_closure(): ...
_testcapi.function_get_closure(function_without_closure), (1, 2))
self.assertEqual(function_without_closure.__closure__, (1, 2))

def test_function_get_annotations(self):
# Test PyFunction_GetAnnotations()
def normal():
pass

def annofn(arg: int) -> str:
return f'arg = {arg}'

annotations = _testcapi.function_get_annotations(normal)
self.assertIsNone(annotations)

annotations = _testcapi.function_get_annotations(annofn)
self.assertIsInstance(annotations, dict)
self.assertEqual(annotations, annofn.__annotations__)

with self.assertRaises(SystemError):
_testcapi.function_get_annotations(None)

# TODO: test PyFunction_New()
# TODO: test PyFunction_NewWithQualName()
# TODO: test PyFunction_SetVectorcall()
# TODO: test PyFunction_GetAnnotations()
# TODO: test PyFunction_SetAnnotations()
# TODO: test PyClassMethod_New()
# TODO: test PyStaticMethod_New()
Expand Down
13 changes: 13 additions & 0 deletions Modules/_testcapi/function.c
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,18 @@ function_set_closure(PyObject *self, PyObject *args)
}


static PyObject *
function_get_annotations(PyObject *self, PyObject *func)
{
PyObject *annotations = PyFunction_GetAnnotations(func);
if (annotations != NULL) {
Comment on lines +129 to +130
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like this whole function can be rewritten as return Py_XNewRef(PyFunction_GetAnnotations(func)).

return Py_NewRef(annotations);
} else {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
} else {
}
else {

return NULL;
}
}


static PyMethodDef test_methods[] = {
{"function_get_code", function_get_code, METH_O, NULL},
{"function_get_globals", function_get_globals, METH_O, NULL},
Expand All @@ -133,6 +145,7 @@ static PyMethodDef test_methods[] = {
{"function_set_kw_defaults", function_set_kw_defaults, METH_VARARGS, NULL},
{"function_get_closure", function_get_closure, METH_O, NULL},
{"function_set_closure", function_set_closure, METH_VARARGS, NULL},
{"function_get_annotations", function_get_annotations, METH_O, NULL},
{NULL},
};

Expand Down
Loading