blob: 801478ade22f6b0b95f07ed3bfa7424eddc42545 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Function object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Victor Stinner44085a32021-02-18 19:20:16 +01005#include "pycore_ceval.h" // _PyEval_BuiltinsFromGlobals()
6#include "pycore_object.h" // _PyObject_GC_UNTRACK()
Victor Stinner46496f92021-02-20 15:17:18 +01007#include "pycore_pyerrors.h" // _PyErr_Occurred()
Victor Stinner4a21e572020-04-15 02:35:41 +02008#include "structmember.h" // PyMemberDef
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Guido van Rossumc0b618a1997-05-02 03:12:38 +000010PyObject *
Antoine Pitrou86a36b52011-11-25 18:56:07 +010011PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012{
Victor Stinner44085a32021-02-18 19:20:16 +010013 assert(globals != NULL);
14 assert(PyDict_Check(globals));
15 Py_INCREF(globals);
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +000016
Victor Stinner46496f92021-02-20 15:17:18 +010017 PyThreadState *tstate = _PyThreadState_GET();
18
Victor Stinner44085a32021-02-18 19:20:16 +010019 PyCodeObject *code_obj = (PyCodeObject *)code;
20 Py_INCREF(code_obj);
21
22 PyObject *name = code_obj->co_name;
23 assert(name != NULL);
24 Py_INCREF(name);
25 if (!qualname) {
26 qualname = name;
27 }
28 Py_INCREF(qualname);
29
30 PyObject *consts = code_obj->co_consts;
31 assert(PyTuple_Check(consts));
32 PyObject *doc;
33 if (PyTuple_Size(consts) >= 1) {
34 doc = PyTuple_GetItem(consts, 0);
35 if (!PyUnicode_Check(doc)) {
36 doc = Py_None;
37 }
38 }
39 else {
40 doc = Py_None;
41 }
42 Py_INCREF(doc);
43
44 // __module__: Use globals['__name__'] if it exists, or NULL.
45 _Py_IDENTIFIER(__name__);
46 PyObject *module = _PyDict_GetItemIdWithError(globals, &PyId___name__);
47 PyObject *builtins = NULL;
Victor Stinner46496f92021-02-20 15:17:18 +010048 if (module == NULL && _PyErr_Occurred(tstate)) {
Victor Stinner44085a32021-02-18 19:20:16 +010049 goto error;
50 }
51 Py_XINCREF(module);
52
Victor Stinnerfc980e02021-03-18 14:51:24 +010053 builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
Victor Stinner44085a32021-02-18 19:20:16 +010054 if (builtins == NULL) {
55 goto error;
Victor Stinner34f96b82013-07-22 23:04:55 +020056 }
Victor Stinner46496f92021-02-20 15:17:18 +010057 Py_INCREF(builtins);
Victor Stinner34f96b82013-07-22 23:04:55 +020058
Victor Stinner44085a32021-02-18 19:20:16 +010059 PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
Yonatan Goldschmidt35052612020-10-29 11:58:52 +020060 if (op == NULL) {
Victor Stinner44085a32021-02-18 19:20:16 +010061 goto error;
Yonatan Goldschmidt35052612020-10-29 11:58:52 +020062 }
63 /* Note: No failures from this point on, since func_dealloc() does not
64 expect a partially-created object. */
Victor Stinner4d1f5d62013-07-22 23:02:05 +020065
Victor Stinner4d1f5d62013-07-22 23:02:05 +020066 op->func_globals = globals;
Mark Shannond6c33fb2021-01-29 13:24:55 +000067 op->func_builtins = builtins;
Victor Stinner44085a32021-02-18 19:20:16 +010068 op->func_name = name;
69 op->func_qualname = qualname;
70 op->func_code = (PyObject*)code_obj;
71 op->func_defaults = NULL; // No default positional arguments
72 op->func_kwdefaults = NULL; // No default keyword arguments
Victor Stinner4d1f5d62013-07-22 23:02:05 +020073 op->func_closure = NULL;
Victor Stinner4d1f5d62013-07-22 23:02:05 +020074 op->func_doc = doc;
75 op->func_dict = NULL;
Victor Stinner44085a32021-02-18 19:20:16 +010076 op->func_weakreflist = NULL;
77 op->func_module = module;
Victor Stinner4d1f5d62013-07-22 23:02:05 +020078 op->func_annotations = NULL;
Victor Stinner44085a32021-02-18 19:20:16 +010079 op->vectorcall = _PyFunction_Vectorcall;
Victor Stinner4d1f5d62013-07-22 23:02:05 +020080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 _PyObject_GC_TRACK(op);
82 return (PyObject *)op;
Victor Stinner44085a32021-02-18 19:20:16 +010083
84error:
85 Py_DECREF(globals);
86 Py_DECREF(code_obj);
87 Py_DECREF(name);
88 Py_DECREF(qualname);
89 Py_DECREF(doc);
90 Py_XDECREF(module);
91 Py_XDECREF(builtins);
92 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000093}
94
Guido van Rossumc0b618a1997-05-02 03:12:38 +000095PyObject *
Antoine Pitrou86a36b52011-11-25 18:56:07 +010096PyFunction_New(PyObject *code, PyObject *globals)
97{
98 return PyFunction_NewWithQualName(code, globals, NULL);
99}
100
101PyObject *
Fred Drakeee238b92000-07-09 06:03:25 +0000102PyFunction_GetCode(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 if (!PyFunction_Check(op)) {
105 PyErr_BadInternalCall();
106 return NULL;
107 }
108 return ((PyFunctionObject *) op) -> func_code;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000109}
110
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000111PyObject *
Fred Drakeee238b92000-07-09 06:03:25 +0000112PyFunction_GetGlobals(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 if (!PyFunction_Check(op)) {
115 PyErr_BadInternalCall();
116 return NULL;
117 }
118 return ((PyFunctionObject *) op) -> func_globals;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000119}
120
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000121PyObject *
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000122PyFunction_GetModule(PyObject *op)
123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 if (!PyFunction_Check(op)) {
125 PyErr_BadInternalCall();
126 return NULL;
127 }
128 return ((PyFunctionObject *) op) -> func_module;
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000129}
130
131PyObject *
Fred Drakeee238b92000-07-09 06:03:25 +0000132PyFunction_GetDefaults(PyObject *op)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 if (!PyFunction_Check(op)) {
135 PyErr_BadInternalCall();
136 return NULL;
137 }
138 return ((PyFunctionObject *) op) -> func_defaults;
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000139}
140
141int
Fred Drakeee238b92000-07-09 06:03:25 +0000142PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 if (!PyFunction_Check(op)) {
145 PyErr_BadInternalCall();
146 return -1;
147 }
148 if (defaults == Py_None)
149 defaults = NULL;
150 else if (defaults && PyTuple_Check(defaults)) {
151 Py_INCREF(defaults);
152 }
153 else {
154 PyErr_SetString(PyExc_SystemError, "non-tuple default args");
155 return -1;
156 }
Serhiy Storchaka48842712016-04-06 09:45:48 +0300157 Py_XSETREF(((PyFunctionObject *)op)->func_defaults, defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 return 0;
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000159}
160
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000161PyObject *
Guido van Rossum4f72a782006-10-27 23:31:49 +0000162PyFunction_GetKwDefaults(PyObject *op)
163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 if (!PyFunction_Check(op)) {
165 PyErr_BadInternalCall();
166 return NULL;
167 }
168 return ((PyFunctionObject *) op) -> func_kwdefaults;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000169}
170
171int
172PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults)
173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 if (!PyFunction_Check(op)) {
175 PyErr_BadInternalCall();
176 return -1;
177 }
178 if (defaults == Py_None)
179 defaults = NULL;
180 else if (defaults && PyDict_Check(defaults)) {
181 Py_INCREF(defaults);
182 }
183 else {
184 PyErr_SetString(PyExc_SystemError,
185 "non-dict keyword only default args");
186 return -1;
187 }
Serhiy Storchaka48842712016-04-06 09:45:48 +0300188 Py_XSETREF(((PyFunctionObject *)op)->func_kwdefaults, defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000190}
191
192PyObject *
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000193PyFunction_GetClosure(PyObject *op)
194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 if (!PyFunction_Check(op)) {
196 PyErr_BadInternalCall();
197 return NULL;
198 }
199 return ((PyFunctionObject *) op) -> func_closure;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000200}
201
202int
203PyFunction_SetClosure(PyObject *op, PyObject *closure)
204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 if (!PyFunction_Check(op)) {
206 PyErr_BadInternalCall();
207 return -1;
208 }
209 if (closure == Py_None)
210 closure = NULL;
211 else if (PyTuple_Check(closure)) {
212 Py_INCREF(closure);
213 }
214 else {
215 PyErr_Format(PyExc_SystemError,
216 "expected tuple for closure, got '%.100s'",
Victor Stinner58ac7002020-02-07 03:04:21 +0100217 Py_TYPE(closure)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 return -1;
219 }
Serhiy Storchaka48842712016-04-06 09:45:48 +0300220 Py_XSETREF(((PyFunctionObject *)op)->func_closure, closure);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 return 0;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000222}
223
Miss Islington (bot)da8be152022-01-05 05:12:21 -0800224static PyObject *
225func_get_annotation_dict(PyFunctionObject *op)
226{
227 if (op->func_annotations == NULL) {
228 return NULL;
229 }
230 if (PyTuple_CheckExact(op->func_annotations)) {
231 PyObject *ann_tuple = op->func_annotations;
232 PyObject *ann_dict = PyDict_New();
233 if (ann_dict == NULL) {
234 return NULL;
235 }
236
237 assert(PyTuple_GET_SIZE(ann_tuple) % 2 == 0);
238
239 for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(ann_tuple); i += 2) {
240 int err = PyDict_SetItem(ann_dict,
241 PyTuple_GET_ITEM(ann_tuple, i),
242 PyTuple_GET_ITEM(ann_tuple, i + 1));
243
244 if (err < 0) {
245 return NULL;
246 }
247 }
248 Py_SETREF(op->func_annotations, ann_dict);
249 }
250 Py_INCREF(op->func_annotations);
251 assert(PyDict_Check(op->func_annotations));
252 return op->func_annotations;
253}
254
Neal Norwitzc1505362006-12-28 06:47:50 +0000255PyObject *
256PyFunction_GetAnnotations(PyObject *op)
257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 if (!PyFunction_Check(op)) {
259 PyErr_BadInternalCall();
260 return NULL;
261 }
Miss Islington (bot)da8be152022-01-05 05:12:21 -0800262 return func_get_annotation_dict((PyFunctionObject *)op);
Neal Norwitzc1505362006-12-28 06:47:50 +0000263}
264
265int
266PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)
267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 if (!PyFunction_Check(op)) {
269 PyErr_BadInternalCall();
270 return -1;
271 }
272 if (annotations == Py_None)
273 annotations = NULL;
274 else if (annotations && PyDict_Check(annotations)) {
275 Py_INCREF(annotations);
276 }
277 else {
278 PyErr_SetString(PyExc_SystemError,
279 "non-dict annotations");
280 return -1;
281 }
Serhiy Storchaka48842712016-04-06 09:45:48 +0300282 Py_XSETREF(((PyFunctionObject *)op)->func_annotations, annotations);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +0000284}
285
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000286/* Methods */
287
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000288#define OFF(x) offsetof(PyFunctionObject, x)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000289
Guido van Rossum6f799372001-09-20 20:46:19 +0000290static PyMemberDef func_memberlist[] = {
Jeroen Demeyer24bba8c2020-02-18 14:14:46 +0100291 {"__closure__", T_OBJECT, OFF(func_closure), READONLY},
292 {"__doc__", T_OBJECT, OFF(func_doc), 0},
293 {"__globals__", T_OBJECT, OFF(func_globals), READONLY},
294 {"__module__", T_OBJECT, OFF(func_module), 0},
Victor Stinnera3c3ffa2021-02-18 12:35:37 +0100295 {"__builtins__", T_OBJECT, OFF(func_builtins), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 {NULL} /* Sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000297};
298
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000299static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200300func_get_code(PyFunctionObject *op, void *Py_UNUSED(ignored))
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000301{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700302 if (PySys_Audit("object.__getattr__", "Os", op, "__code__") < 0) {
303 return NULL;
304 }
305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 Py_INCREF(op->func_code);
307 return op->func_code;
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000308}
309
310static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200311func_set_code(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 Py_ssize_t nfree, nclosure;
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 /* Not legal to del f.func_code or to set it to anything
316 * other than a code object. */
317 if (value == NULL || !PyCode_Check(value)) {
318 PyErr_SetString(PyExc_TypeError,
319 "__code__ must be set to a code object");
320 return -1;
321 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700322
323 if (PySys_Audit("object.__setattr__", "OsO",
324 op, "__code__", value) < 0) {
325 return -1;
326 }
327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 nfree = PyCode_GetNumFree((PyCodeObject *)value);
329 nclosure = (op->func_closure == NULL ? 0 :
330 PyTuple_GET_SIZE(op->func_closure));
331 if (nclosure != nfree) {
332 PyErr_Format(PyExc_ValueError,
333 "%U() requires a code object with %zd free vars,"
334 " not %zd",
335 op->func_name,
336 nclosure, nfree);
337 return -1;
338 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300340 Py_XSETREF(op->func_code, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 return 0;
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000342}
343
344static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200345func_get_name(PyFunctionObject *op, void *Py_UNUSED(ignored))
Michael W. Hudson5e897952004-08-12 18:12:44 +0000346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 Py_INCREF(op->func_name);
348 return op->func_name;
Michael W. Hudson5e897952004-08-12 18:12:44 +0000349}
350
351static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200352func_set_name(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
Michael W. Hudson5e897952004-08-12 18:12:44 +0000353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 /* Not legal to del f.func_name or to set it to anything
355 * other than a string object. */
356 if (value == NULL || !PyUnicode_Check(value)) {
357 PyErr_SetString(PyExc_TypeError,
358 "__name__ must be set to a string object");
359 return -1;
360 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300362 Py_XSETREF(op->func_name, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 return 0;
Michael W. Hudson5e897952004-08-12 18:12:44 +0000364}
365
366static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200367func_get_qualname(PyFunctionObject *op, void *Py_UNUSED(ignored))
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100368{
369 Py_INCREF(op->func_qualname);
370 return op->func_qualname;
371}
372
373static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200374func_set_qualname(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100375{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100376 /* Not legal to del f.__qualname__ or to set it to anything
377 * other than a string object. */
378 if (value == NULL || !PyUnicode_Check(value)) {
379 PyErr_SetString(PyExc_TypeError,
380 "__qualname__ must be set to a string object");
381 return -1;
382 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100383 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300384 Py_XSETREF(op->func_qualname, value);
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100385 return 0;
386}
387
388static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200389func_get_defaults(PyFunctionObject *op, void *Py_UNUSED(ignored))
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000390{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700391 if (PySys_Audit("object.__getattr__", "Os", op, "__defaults__") < 0) {
392 return NULL;
393 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (op->func_defaults == NULL) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200395 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 }
397 Py_INCREF(op->func_defaults);
398 return op->func_defaults;
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000399}
400
401static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200402func_set_defaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 /* Legal to del f.func_defaults.
405 * Can only set func_defaults to NULL or a tuple. */
406 if (value == Py_None)
407 value = NULL;
408 if (value != NULL && !PyTuple_Check(value)) {
409 PyErr_SetString(PyExc_TypeError,
410 "__defaults__ must be set to a tuple object");
411 return -1;
412 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700413 if (value) {
414 if (PySys_Audit("object.__setattr__", "OsO",
415 op, "__defaults__", value) < 0) {
416 return -1;
417 }
418 } else if (PySys_Audit("object.__delattr__", "Os",
419 op, "__defaults__") < 0) {
420 return -1;
421 }
422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 Py_XINCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300424 Py_XSETREF(op->func_defaults, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 return 0;
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000426}
427
Guido van Rossum4f72a782006-10-27 23:31:49 +0000428static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200429func_get_kwdefaults(PyFunctionObject *op, void *Py_UNUSED(ignored))
Guido van Rossum4f72a782006-10-27 23:31:49 +0000430{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700431 if (PySys_Audit("object.__getattr__", "Os",
432 op, "__kwdefaults__") < 0) {
433 return NULL;
434 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 if (op->func_kwdefaults == NULL) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200436 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 }
438 Py_INCREF(op->func_kwdefaults);
439 return op->func_kwdefaults;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000440}
441
442static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200443func_set_kwdefaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
Guido van Rossum4f72a782006-10-27 23:31:49 +0000444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 if (value == Py_None)
446 value = NULL;
447 /* Legal to del f.func_kwdefaults.
448 * Can only set func_kwdefaults to NULL or a dict. */
449 if (value != NULL && !PyDict_Check(value)) {
450 PyErr_SetString(PyExc_TypeError,
451 "__kwdefaults__ must be set to a dict object");
452 return -1;
453 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700454 if (value) {
455 if (PySys_Audit("object.__setattr__", "OsO",
456 op, "__kwdefaults__", value) < 0) {
457 return -1;
458 }
459 } else if (PySys_Audit("object.__delattr__", "Os",
460 op, "__kwdefaults__") < 0) {
461 return -1;
462 }
463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 Py_XINCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300465 Py_XSETREF(op->func_kwdefaults, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000467}
468
Neal Norwitzc1505362006-12-28 06:47:50 +0000469static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200470func_get_annotations(PyFunctionObject *op, void *Py_UNUSED(ignored))
Neal Norwitzc1505362006-12-28 06:47:50 +0000471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 if (op->func_annotations == NULL) {
473 op->func_annotations = PyDict_New();
474 if (op->func_annotations == NULL)
475 return NULL;
476 }
Miss Islington (bot)da8be152022-01-05 05:12:21 -0800477 return func_get_annotation_dict(op);
Neal Norwitzc1505362006-12-28 06:47:50 +0000478}
479
480static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200481func_set_annotations(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
Neal Norwitzc1505362006-12-28 06:47:50 +0000482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 if (value == Py_None)
484 value = NULL;
485 /* Legal to del f.func_annotations.
486 * Can only set func_annotations to NULL (through C api)
487 * or a dict. */
488 if (value != NULL && !PyDict_Check(value)) {
489 PyErr_SetString(PyExc_TypeError,
490 "__annotations__ must be set to a dict object");
491 return -1;
492 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 Py_XINCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300494 Py_XSETREF(op->func_annotations, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +0000496}
497
Guido van Rossum32d34c82001-09-20 21:45:26 +0000498static PyGetSetDef func_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 {"__code__", (getter)func_get_code, (setter)func_set_code},
500 {"__defaults__", (getter)func_get_defaults,
501 (setter)func_set_defaults},
502 {"__kwdefaults__", (getter)func_get_kwdefaults,
503 (setter)func_set_kwdefaults},
504 {"__annotations__", (getter)func_get_annotations,
505 (setter)func_set_annotations},
Benjamin Peterson23d7f122012-02-19 20:02:57 -0500506 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 {"__name__", (getter)func_get_name, (setter)func_set_name},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100508 {"__qualname__", (getter)func_get_qualname, (setter)func_set_qualname},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 {NULL} /* Sentinel */
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000510};
511
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200512/*[clinic input]
513class function "PyFunctionObject *" "&PyFunction_Type"
514[clinic start generated code]*/
515/*[clinic end generated code: output=da39a3ee5e6b4b0d input=70af9c90aa2e71b0]*/
Jeremy Hyltondf3f7932002-07-11 18:30:27 +0000516
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200517#include "clinic/funcobject.c.h"
518
519/* function.__new__() maintains the following invariants for closures.
520 The closure must correspond to the free variables of the code object.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521
522 if len(code.co_freevars) == 0:
523 closure = NULL
Jeremy Hyltondf3f7932002-07-11 18:30:27 +0000524 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 len(closure) == len(code.co_freevars)
Jeremy Hyltondf3f7932002-07-11 18:30:27 +0000526 for every elt in closure, type(elt) == cell
527*/
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000528
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200529/*[clinic input]
530@classmethod
531function.__new__ as func_new
532 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
533 a code object
534 globals: object(subclass_of="&PyDict_Type")
535 the globals dictionary
536 name: object = None
537 a string that overrides the name from the code object
538 argdefs as defaults: object = None
539 a tuple that specifies the default argument values
540 closure: object = None
541 a tuple that supplies the bindings for free variables
542
543Create a function object.
544[clinic start generated code]*/
545
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000546static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200547func_new_impl(PyTypeObject *type, PyCodeObject *code, PyObject *globals,
548 PyObject *name, PyObject *defaults, PyObject *closure)
549/*[clinic end generated code: output=99c6d9da3a24e3be input=93611752fc2daf11]*/
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 PyFunctionObject *newfunc;
552 Py_ssize_t nfree, nclosure;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 if (name != Py_None && !PyUnicode_Check(name)) {
555 PyErr_SetString(PyExc_TypeError,
556 "arg 3 (name) must be None or string");
557 return NULL;
558 }
559 if (defaults != Py_None && !PyTuple_Check(defaults)) {
560 PyErr_SetString(PyExc_TypeError,
561 "arg 4 (defaults) must be None or tuple");
562 return NULL;
563 }
564 nfree = PyTuple_GET_SIZE(code->co_freevars);
565 if (!PyTuple_Check(closure)) {
566 if (nfree && closure == Py_None) {
567 PyErr_SetString(PyExc_TypeError,
568 "arg 5 (closure) must be tuple");
569 return NULL;
570 }
571 else if (closure != Py_None) {
572 PyErr_SetString(PyExc_TypeError,
573 "arg 5 (closure) must be None or tuple");
574 return NULL;
575 }
576 }
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 /* check that the closure is well-formed */
579 nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
580 if (nfree != nclosure)
581 return PyErr_Format(PyExc_ValueError,
582 "%U requires closure of length %zd, not %zd",
583 code->co_name, nfree, nclosure);
584 if (nclosure) {
585 Py_ssize_t i;
586 for (i = 0; i < nclosure; i++) {
587 PyObject *o = PyTuple_GET_ITEM(closure, i);
588 if (!PyCell_Check(o)) {
589 return PyErr_Format(PyExc_TypeError,
590 "arg 5 (closure) expected cell, found %s",
Victor Stinner58ac7002020-02-07 03:04:21 +0100591 Py_TYPE(o)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 }
593 }
594 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700595 if (PySys_Audit("function.__new__", "O", code) < 0) {
596 return NULL;
597 }
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
600 globals);
Mark Shannon0332e562021-02-01 10:42:03 +0000601 if (newfunc == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 return NULL;
Mark Shannon0332e562021-02-01 10:42:03 +0000603 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 if (name != Py_None) {
605 Py_INCREF(name);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300606 Py_SETREF(newfunc->func_name, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 }
608 if (defaults != Py_None) {
609 Py_INCREF(defaults);
610 newfunc->func_defaults = defaults;
611 }
612 if (closure != Py_None) {
613 Py_INCREF(closure);
614 newfunc->func_closure = closure;
615 }
616
617 return (PyObject *)newfunc;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000618}
619
INADA Naoki3c452402018-07-04 11:15:50 +0900620static int
621func_clear(PyFunctionObject *op)
622{
623 Py_CLEAR(op->func_code);
624 Py_CLEAR(op->func_globals);
Mark Shannond6c33fb2021-01-29 13:24:55 +0000625 Py_CLEAR(op->func_builtins);
INADA Naoki3c452402018-07-04 11:15:50 +0900626 Py_CLEAR(op->func_name);
Mark Shannond6c33fb2021-01-29 13:24:55 +0000627 Py_CLEAR(op->func_qualname);
628 Py_CLEAR(op->func_module);
INADA Naoki3c452402018-07-04 11:15:50 +0900629 Py_CLEAR(op->func_defaults);
630 Py_CLEAR(op->func_kwdefaults);
631 Py_CLEAR(op->func_doc);
632 Py_CLEAR(op->func_dict);
633 Py_CLEAR(op->func_closure);
634 Py_CLEAR(op->func_annotations);
INADA Naoki3c452402018-07-04 11:15:50 +0900635 return 0;
636}
637
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000638static void
Fred Drakeee238b92000-07-09 06:03:25 +0000639func_dealloc(PyFunctionObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 _PyObject_GC_UNTRACK(op);
INADA Naoki3c452402018-07-04 11:15:50 +0900642 if (op->func_weakreflist != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 PyObject_ClearWeakRefs((PyObject *) op);
INADA Naoki3c452402018-07-04 11:15:50 +0900644 }
645 (void)func_clear(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyObject_GC_Del(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000647}
648
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000649static PyObject*
Fred Drakeee238b92000-07-09 06:03:25 +0000650func_repr(PyFunctionObject *op)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 return PyUnicode_FromFormat("<function %U at %p>",
Victor Stinner507a5742021-04-09 17:51:22 +0200653 op->func_qualname, op);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000654}
655
Guido van Rossum2e8f8a31993-11-05 10:20:10 +0000656static int
Jeremy Hylton8caad492000-06-23 14:18:11 +0000657func_traverse(PyFunctionObject *f, visitproc visit, void *arg)
658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 Py_VISIT(f->func_code);
660 Py_VISIT(f->func_globals);
Mark Shannond6c33fb2021-01-29 13:24:55 +0000661 Py_VISIT(f->func_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 Py_VISIT(f->func_module);
663 Py_VISIT(f->func_defaults);
664 Py_VISIT(f->func_kwdefaults);
665 Py_VISIT(f->func_doc);
666 Py_VISIT(f->func_name);
667 Py_VISIT(f->func_dict);
668 Py_VISIT(f->func_closure);
669 Py_VISIT(f->func_annotations);
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100670 Py_VISIT(f->func_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +0000672}
673
Tim Peters6d6c1a32001-08-02 04:15:00 +0000674/* Bind a function to an object */
675static PyObject *
676func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 if (obj == Py_None || obj == NULL) {
679 Py_INCREF(func);
680 return func;
681 }
682 return PyMethod_New(func, obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000683}
684
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000685PyTypeObject PyFunction_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 PyVarObject_HEAD_INIT(&PyType_Type, 0)
687 "function",
688 sizeof(PyFunctionObject),
689 0,
690 (destructor)func_dealloc, /* tp_dealloc */
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +0200691 offsetof(PyFunctionObject, vectorcall), /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 0, /* tp_getattr */
693 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200694 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 (reprfunc)func_repr, /* tp_repr */
696 0, /* tp_as_number */
697 0, /* tp_as_sequence */
698 0, /* tp_as_mapping */
699 0, /* tp_hash */
Jeroen Demeyer59543342019-06-18 13:05:41 +0200700 PyVectorcall_Call, /* tp_call */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 0, /* tp_str */
Benjamin Peterson2cf936f2012-02-19 01:16:13 -0500702 0, /* tp_getattro */
703 0, /* tp_setattro */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 0, /* tp_as_buffer */
Jeroen Demeyereb65e242019-05-28 14:42:53 +0200705 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Petr Viktorinffd97532020-02-11 17:46:57 +0100706 Py_TPFLAGS_HAVE_VECTORCALL |
Jeroen Demeyereb65e242019-05-28 14:42:53 +0200707 Py_TPFLAGS_METHOD_DESCRIPTOR, /* tp_flags */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200708 func_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 (traverseproc)func_traverse, /* tp_traverse */
INADA Naoki3c452402018-07-04 11:15:50 +0900710 (inquiry)func_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 0, /* tp_richcompare */
712 offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
713 0, /* tp_iter */
714 0, /* tp_iternext */
715 0, /* tp_methods */
716 func_memberlist, /* tp_members */
717 func_getsetlist, /* tp_getset */
718 0, /* tp_base */
719 0, /* tp_dict */
720 func_descr_get, /* tp_descr_get */
721 0, /* tp_descr_set */
722 offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */
723 0, /* tp_init */
724 0, /* tp_alloc */
725 func_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000726};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000727
728
Victor Stinner507a5742021-04-09 17:51:22 +0200729static int
730functools_copy_attr(PyObject *wrapper, PyObject *wrapped, PyObject *name)
731{
732 PyObject *value = PyObject_GetAttr(wrapped, name);
733 if (value == NULL) {
734 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
735 PyErr_Clear();
736 return 0;
737 }
738 return -1;
739 }
740
741 int res = PyObject_SetAttr(wrapper, name, value);
742 Py_DECREF(value);
743 return res;
744}
745
746// Similar to functools.wraps(wrapper, wrapped)
747static int
748functools_wraps(PyObject *wrapper, PyObject *wrapped)
749{
750#define COPY_ATTR(ATTR) \
751 do { \
752 _Py_IDENTIFIER(ATTR); \
753 PyObject *attr = _PyUnicode_FromId(&PyId_ ## ATTR); \
754 if (attr == NULL) { \
755 return -1; \
756 } \
757 if (functools_copy_attr(wrapper, wrapped, attr) < 0) { \
758 return -1; \
759 } \
760 } while (0) \
761
762 COPY_ATTR(__module__);
763 COPY_ATTR(__name__);
764 COPY_ATTR(__qualname__);
765 COPY_ATTR(__doc__);
766 COPY_ATTR(__annotations__);
767 return 0;
768
769#undef COPY_ATTR
770}
771
772
Tim Peters6d6c1a32001-08-02 04:15:00 +0000773/* Class method object */
774
775/* A class method receives the class as implicit first argument,
776 just like an instance method receives the instance.
777 To declare a class method, use this idiom:
778
779 class C:
Martin Panter6d57fe12016-09-17 03:26:16 +0000780 @classmethod
781 def f(cls, arg1, arg2, ...):
782 ...
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783
Tim Peters6d6c1a32001-08-02 04:15:00 +0000784 It can be called either on the class (e.g. C.f()) or on an instance
785 (e.g. C().f()); the instance is ignored except for its class.
786 If a class method is called for a derived class, the derived class
787 object is passed as the implied first argument.
788
789 Class methods are different than C++ or Java static methods.
790 If you want those, see static methods below.
791*/
792
793typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 PyObject_HEAD
795 PyObject *cm_callable;
Benjamin Peterson01d7eba2012-02-19 01:10:25 -0500796 PyObject *cm_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000797} classmethod;
798
799static void
800cm_dealloc(classmethod *cm)
801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 _PyObject_GC_UNTRACK((PyObject *)cm);
803 Py_XDECREF(cm->cm_callable);
Benjamin Peterson01d7eba2012-02-19 01:10:25 -0500804 Py_XDECREF(cm->cm_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 Py_TYPE(cm)->tp_free((PyObject *)cm);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000806}
807
Jeremy Hylton400d8ee2003-04-08 21:28:47 +0000808static int
809cm_traverse(classmethod *cm, visitproc visit, void *arg)
810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 Py_VISIT(cm->cm_callable);
Benjamin Peterson01d7eba2012-02-19 01:10:25 -0500812 Py_VISIT(cm->cm_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 return 0;
Jeremy Hylton400d8ee2003-04-08 21:28:47 +0000814}
815
816static int
817cm_clear(classmethod *cm)
818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 Py_CLEAR(cm->cm_callable);
Benjamin Peterson01d7eba2012-02-19 01:10:25 -0500820 Py_CLEAR(cm->cm_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 return 0;
Jeremy Hylton400d8ee2003-04-08 21:28:47 +0000822}
823
824
Tim Peters6d6c1a32001-08-02 04:15:00 +0000825static PyObject *
826cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 classmethod *cm = (classmethod *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if (cm->cm_callable == NULL) {
831 PyErr_SetString(PyExc_RuntimeError,
832 "uninitialized classmethod object");
833 return NULL;
834 }
835 if (type == NULL)
836 type = (PyObject *)(Py_TYPE(obj));
Berker Peksag805f8f92019-08-25 01:37:25 +0300837 if (Py_TYPE(cm->cm_callable)->tp_descr_get != NULL) {
838 return Py_TYPE(cm->cm_callable)->tp_descr_get(cm->cm_callable, type,
Miss Islington (bot)2ce8af32021-07-15 06:42:11 -0700839 type);
Berker Peksag805f8f92019-08-25 01:37:25 +0300840 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 return PyMethod_New(cm->cm_callable, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000842}
843
844static int
845cm_init(PyObject *self, PyObject *args, PyObject *kwds)
846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 classmethod *cm = (classmethod *)self;
848 PyObject *callable;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 if (!_PyArg_NoKeywords("classmethod", kwds))
851 return -1;
Sylvain96480882017-07-09 05:45:06 +0200852 if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable))
853 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 Py_INCREF(callable);
Oren Milmand019bc82018-02-13 12:28:33 +0200855 Py_XSETREF(cm->cm_callable, callable);
Victor Stinner507a5742021-04-09 17:51:22 +0200856
857 if (functools_wraps((PyObject *)cm, cm->cm_callable) < 0) {
858 return -1;
859 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000861}
862
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000863static PyMemberDef cm_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY},
Victor Stinner507a5742021-04-09 17:51:22 +0200865 {"__wrapped__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 {NULL} /* Sentinel */
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000867};
868
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500869static PyObject *
870cm_get___isabstractmethod__(classmethod *cm, void *closure)
871{
872 int res = _PyObject_IsAbstract(cm->cm_callable);
873 if (res == -1) {
874 return NULL;
875 }
876 else if (res) {
877 Py_RETURN_TRUE;
878 }
879 Py_RETURN_FALSE;
880}
881
882static PyGetSetDef cm_getsetlist[] = {
883 {"__isabstractmethod__",
Victor Stinner507a5742021-04-09 17:51:22 +0200884 (getter)cm_get___isabstractmethod__, NULL, NULL, NULL},
Benjamin Peterson23d7f122012-02-19 20:02:57 -0500885 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500886 {NULL} /* Sentinel */
887};
888
Victor Stinner507a5742021-04-09 17:51:22 +0200889static PyObject*
890cm_repr(classmethod *cm)
891{
892 return PyUnicode_FromFormat("<classmethod(%R)>", cm->cm_callable);
893}
894
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000895PyDoc_STRVAR(classmethod_doc,
Guido van Rossum33c1a882001-12-17 02:53:53 +0000896"classmethod(function) -> method\n\
897\n\
898Convert a function to be a class method.\n\
899\n\
900A class method receives the class as implicit first argument,\n\
901just like an instance method receives the instance.\n\
902To declare a class method, use this idiom:\n\
903\n\
904 class C:\n\
Martin Panter6d57fe12016-09-17 03:26:16 +0000905 @classmethod\n\
906 def f(cls, arg1, arg2, ...):\n\
907 ...\n\
Guido van Rossum33c1a882001-12-17 02:53:53 +0000908\n\
909It can be called either on the class (e.g. C.f()) or on an instance\n\
910(e.g. C().f()). The instance is ignored except for its class.\n\
911If a class method is called for a derived class, the derived class\n\
912object is passed as the implied first argument.\n\
Sjoerd Mullender564980b2001-12-17 11:39:56 +0000913\n\
Guido van Rossum33c1a882001-12-17 02:53:53 +0000914Class methods are different than C++ or Java static methods.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000915If you want those, see the staticmethod builtin.");
Guido van Rossum33c1a882001-12-17 02:53:53 +0000916
Tim Peters6d6c1a32001-08-02 04:15:00 +0000917PyTypeObject PyClassMethod_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 PyVarObject_HEAD_INIT(&PyType_Type, 0)
919 "classmethod",
920 sizeof(classmethod),
921 0,
922 (destructor)cm_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200923 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 0, /* tp_getattr */
925 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200926 0, /* tp_as_async */
Victor Stinner507a5742021-04-09 17:51:22 +0200927 (reprfunc)cm_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 0, /* tp_as_number */
929 0, /* tp_as_sequence */
930 0, /* tp_as_mapping */
931 0, /* tp_hash */
932 0, /* tp_call */
933 0, /* tp_str */
Benjamin Peterson2cf936f2012-02-19 01:16:13 -0500934 0, /* tp_getattro */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 0, /* tp_setattro */
936 0, /* tp_as_buffer */
937 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
938 classmethod_doc, /* tp_doc */
939 (traverseproc)cm_traverse, /* tp_traverse */
940 (inquiry)cm_clear, /* tp_clear */
941 0, /* tp_richcompare */
942 0, /* tp_weaklistoffset */
943 0, /* tp_iter */
944 0, /* tp_iternext */
945 0, /* tp_methods */
946 cm_memberlist, /* tp_members */
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500947 cm_getsetlist, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 0, /* tp_base */
949 0, /* tp_dict */
950 cm_descr_get, /* tp_descr_get */
951 0, /* tp_descr_set */
Benjamin Peterson01d7eba2012-02-19 01:10:25 -0500952 offsetof(classmethod, cm_dict), /* tp_dictoffset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 cm_init, /* tp_init */
954 PyType_GenericAlloc, /* tp_alloc */
955 PyType_GenericNew, /* tp_new */
956 PyObject_GC_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000957};
958
959PyObject *
960PyClassMethod_New(PyObject *callable)
961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 classmethod *cm = (classmethod *)
963 PyType_GenericAlloc(&PyClassMethod_Type, 0);
964 if (cm != NULL) {
965 Py_INCREF(callable);
966 cm->cm_callable = callable;
967 }
968 return (PyObject *)cm;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000969}
970
971
972/* Static method object */
973
974/* A static method does not receive an implicit first argument.
975 To declare a static method, use this idiom:
976
977 class C:
Martin Panter6d57fe12016-09-17 03:26:16 +0000978 @staticmethod
979 def f(arg1, arg2, ...):
980 ...
Tim Peters6d6c1a32001-08-02 04:15:00 +0000981
982 It can be called either on the class (e.g. C.f()) or on an instance
Jess Shapiroe7eed782018-12-23 23:47:38 -0800983 (e.g. C().f()). Both the class and the instance are ignored, and
984 neither is passed implicitly as the first argument to the method.
Tim Peters6d6c1a32001-08-02 04:15:00 +0000985
986 Static methods in Python are similar to those found in Java or C++.
987 For a more advanced concept, see class methods above.
988*/
989
990typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 PyObject_HEAD
992 PyObject *sm_callable;
Benjamin Peterson01d7eba2012-02-19 01:10:25 -0500993 PyObject *sm_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000994} staticmethod;
995
996static void
997sm_dealloc(staticmethod *sm)
998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 _PyObject_GC_UNTRACK((PyObject *)sm);
1000 Py_XDECREF(sm->sm_callable);
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001001 Py_XDECREF(sm->sm_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 Py_TYPE(sm)->tp_free((PyObject *)sm);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001003}
1004
Jeremy Hylton400d8ee2003-04-08 21:28:47 +00001005static int
1006sm_traverse(staticmethod *sm, visitproc visit, void *arg)
1007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 Py_VISIT(sm->sm_callable);
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001009 Py_VISIT(sm->sm_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 return 0;
Jeremy Hylton400d8ee2003-04-08 21:28:47 +00001011}
1012
1013static int
1014sm_clear(staticmethod *sm)
1015{
Benjamin Peterson496c53d2012-02-19 01:11:56 -05001016 Py_CLEAR(sm->sm_callable);
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001017 Py_CLEAR(sm->sm_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 return 0;
Jeremy Hylton400d8ee2003-04-08 21:28:47 +00001019}
1020
Tim Peters6d6c1a32001-08-02 04:15:00 +00001021static PyObject *
1022sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
1023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 staticmethod *sm = (staticmethod *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 if (sm->sm_callable == NULL) {
1027 PyErr_SetString(PyExc_RuntimeError,
1028 "uninitialized staticmethod object");
1029 return NULL;
1030 }
1031 Py_INCREF(sm->sm_callable);
1032 return sm->sm_callable;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001033}
1034
1035static int
1036sm_init(PyObject *self, PyObject *args, PyObject *kwds)
1037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 staticmethod *sm = (staticmethod *)self;
1039 PyObject *callable;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 if (!_PyArg_NoKeywords("staticmethod", kwds))
1042 return -1;
Sylvain96480882017-07-09 05:45:06 +02001043 if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable))
1044 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 Py_INCREF(callable);
Oren Milmand019bc82018-02-13 12:28:33 +02001046 Py_XSETREF(sm->sm_callable, callable);
Victor Stinner507a5742021-04-09 17:51:22 +02001047
1048 if (functools_wraps((PyObject *)sm, sm->sm_callable) < 0) {
1049 return -1;
1050 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001052}
1053
Victor Stinner553ee272021-04-12 00:21:22 +02001054static PyObject*
1055sm_call(PyObject *callable, PyObject *args, PyObject *kwargs)
1056{
1057 staticmethod *sm = (staticmethod *)callable;
1058 return PyObject_Call(sm->sm_callable, args, kwargs);
1059}
1060
Raymond Hettinger2bcde142009-05-29 04:52:27 +00001061static PyMemberDef sm_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY},
Victor Stinner507a5742021-04-09 17:51:22 +02001063 {"__wrapped__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 {NULL} /* Sentinel */
Raymond Hettinger2bcde142009-05-29 04:52:27 +00001065};
1066
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -05001067static PyObject *
1068sm_get___isabstractmethod__(staticmethod *sm, void *closure)
1069{
1070 int res = _PyObject_IsAbstract(sm->sm_callable);
1071 if (res == -1) {
1072 return NULL;
1073 }
1074 else if (res) {
1075 Py_RETURN_TRUE;
1076 }
1077 Py_RETURN_FALSE;
1078}
1079
1080static PyGetSetDef sm_getsetlist[] = {
1081 {"__isabstractmethod__",
Victor Stinner507a5742021-04-09 17:51:22 +02001082 (getter)sm_get___isabstractmethod__, NULL, NULL, NULL},
Benjamin Peterson23d7f122012-02-19 20:02:57 -05001083 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -05001084 {NULL} /* Sentinel */
1085};
1086
Victor Stinner507a5742021-04-09 17:51:22 +02001087static PyObject*
1088sm_repr(staticmethod *sm)
1089{
1090 return PyUnicode_FromFormat("<staticmethod(%R)>", sm->sm_callable);
1091}
1092
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001093PyDoc_STRVAR(staticmethod_doc,
Guido van Rossum33c1a882001-12-17 02:53:53 +00001094"staticmethod(function) -> method\n\
1095\n\
1096Convert a function to be a static method.\n\
1097\n\
1098A static method does not receive an implicit first argument.\n\
1099To declare a static method, use this idiom:\n\
1100\n\
1101 class C:\n\
Martin Panter6d57fe12016-09-17 03:26:16 +00001102 @staticmethod\n\
1103 def f(arg1, arg2, ...):\n\
1104 ...\n\
Guido van Rossum33c1a882001-12-17 02:53:53 +00001105\n\
1106It can be called either on the class (e.g. C.f()) or on an instance\n\
Jess Shapiroe7eed782018-12-23 23:47:38 -08001107(e.g. C().f()). Both the class and the instance are ignored, and\n\
1108neither is passed implicitly as the first argument to the method.\n\
Guido van Rossum33c1a882001-12-17 02:53:53 +00001109\n\
1110Static methods in Python are similar to those found in Java or C++.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001111For a more advanced concept, see the classmethod builtin.");
Guido van Rossum33c1a882001-12-17 02:53:53 +00001112
Tim Peters6d6c1a32001-08-02 04:15:00 +00001113PyTypeObject PyStaticMethod_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1115 "staticmethod",
1116 sizeof(staticmethod),
1117 0,
1118 (destructor)sm_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001119 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 0, /* tp_getattr */
1121 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001122 0, /* tp_as_async */
Victor Stinner507a5742021-04-09 17:51:22 +02001123 (reprfunc)sm_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 0, /* tp_as_number */
1125 0, /* tp_as_sequence */
1126 0, /* tp_as_mapping */
1127 0, /* tp_hash */
Victor Stinner553ee272021-04-12 00:21:22 +02001128 sm_call, /* tp_call */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 0, /* tp_str */
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001130 0, /* tp_getattro */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 0, /* tp_setattro */
1132 0, /* tp_as_buffer */
1133 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1134 staticmethod_doc, /* tp_doc */
1135 (traverseproc)sm_traverse, /* tp_traverse */
1136 (inquiry)sm_clear, /* tp_clear */
1137 0, /* tp_richcompare */
1138 0, /* tp_weaklistoffset */
1139 0, /* tp_iter */
1140 0, /* tp_iternext */
1141 0, /* tp_methods */
1142 sm_memberlist, /* tp_members */
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -05001143 sm_getsetlist, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 0, /* tp_base */
1145 0, /* tp_dict */
1146 sm_descr_get, /* tp_descr_get */
1147 0, /* tp_descr_set */
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001148 offsetof(staticmethod, sm_dict), /* tp_dictoffset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 sm_init, /* tp_init */
1150 PyType_GenericAlloc, /* tp_alloc */
1151 PyType_GenericNew, /* tp_new */
1152 PyObject_GC_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001153};
1154
1155PyObject *
1156PyStaticMethod_New(PyObject *callable)
1157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 staticmethod *sm = (staticmethod *)
1159 PyType_GenericAlloc(&PyStaticMethod_Type, 0);
1160 if (sm != NULL) {
1161 Py_INCREF(callable);
1162 sm->sm_callable = callable;
1163 }
1164 return (PyObject *)sm;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001165}