blob: df59131912190bbf80fb4eedac4dd9019d551db2 [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
Neal Norwitzc1505362006-12-28 06:47:50 +0000224PyObject *
225PyFunction_GetAnnotations(PyObject *op)
226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 if (!PyFunction_Check(op)) {
228 PyErr_BadInternalCall();
229 return NULL;
230 }
231 return ((PyFunctionObject *) op) -> func_annotations;
Neal Norwitzc1505362006-12-28 06:47:50 +0000232}
233
234int
235PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)
236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 if (!PyFunction_Check(op)) {
238 PyErr_BadInternalCall();
239 return -1;
240 }
241 if (annotations == Py_None)
242 annotations = NULL;
243 else if (annotations && PyDict_Check(annotations)) {
244 Py_INCREF(annotations);
245 }
246 else {
247 PyErr_SetString(PyExc_SystemError,
248 "non-dict annotations");
249 return -1;
250 }
Serhiy Storchaka48842712016-04-06 09:45:48 +0300251 Py_XSETREF(((PyFunctionObject *)op)->func_annotations, annotations);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +0000253}
254
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000255/* Methods */
256
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000257#define OFF(x) offsetof(PyFunctionObject, x)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000258
Guido van Rossum6f799372001-09-20 20:46:19 +0000259static PyMemberDef func_memberlist[] = {
Jeroen Demeyer24bba8c2020-02-18 14:14:46 +0100260 {"__closure__", T_OBJECT, OFF(func_closure), READONLY},
261 {"__doc__", T_OBJECT, OFF(func_doc), 0},
262 {"__globals__", T_OBJECT, OFF(func_globals), READONLY},
263 {"__module__", T_OBJECT, OFF(func_module), 0},
Victor Stinnera3c3ffa2021-02-18 12:35:37 +0100264 {"__builtins__", T_OBJECT, OFF(func_builtins), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 {NULL} /* Sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000266};
267
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000268static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200269func_get_code(PyFunctionObject *op, void *Py_UNUSED(ignored))
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000270{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700271 if (PySys_Audit("object.__getattr__", "Os", op, "__code__") < 0) {
272 return NULL;
273 }
274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 Py_INCREF(op->func_code);
276 return op->func_code;
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000277}
278
279static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200280func_set_code(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 Py_ssize_t nfree, nclosure;
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 /* Not legal to del f.func_code or to set it to anything
285 * other than a code object. */
286 if (value == NULL || !PyCode_Check(value)) {
287 PyErr_SetString(PyExc_TypeError,
288 "__code__ must be set to a code object");
289 return -1;
290 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700291
292 if (PySys_Audit("object.__setattr__", "OsO",
293 op, "__code__", value) < 0) {
294 return -1;
295 }
296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 nfree = PyCode_GetNumFree((PyCodeObject *)value);
298 nclosure = (op->func_closure == NULL ? 0 :
299 PyTuple_GET_SIZE(op->func_closure));
300 if (nclosure != nfree) {
301 PyErr_Format(PyExc_ValueError,
302 "%U() requires a code object with %zd free vars,"
303 " not %zd",
304 op->func_name,
305 nclosure, nfree);
306 return -1;
307 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300309 Py_XSETREF(op->func_code, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 return 0;
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000311}
312
313static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200314func_get_name(PyFunctionObject *op, void *Py_UNUSED(ignored))
Michael W. Hudson5e897952004-08-12 18:12:44 +0000315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 Py_INCREF(op->func_name);
317 return op->func_name;
Michael W. Hudson5e897952004-08-12 18:12:44 +0000318}
319
320static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200321func_set_name(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
Michael W. Hudson5e897952004-08-12 18:12:44 +0000322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 /* Not legal to del f.func_name or to set it to anything
324 * other than a string object. */
325 if (value == NULL || !PyUnicode_Check(value)) {
326 PyErr_SetString(PyExc_TypeError,
327 "__name__ must be set to a string object");
328 return -1;
329 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300331 Py_XSETREF(op->func_name, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 return 0;
Michael W. Hudson5e897952004-08-12 18:12:44 +0000333}
334
335static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200336func_get_qualname(PyFunctionObject *op, void *Py_UNUSED(ignored))
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100337{
338 Py_INCREF(op->func_qualname);
339 return op->func_qualname;
340}
341
342static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200343func_set_qualname(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100344{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100345 /* Not legal to del f.__qualname__ or to set it to anything
346 * other than a string object. */
347 if (value == NULL || !PyUnicode_Check(value)) {
348 PyErr_SetString(PyExc_TypeError,
349 "__qualname__ must be set to a string object");
350 return -1;
351 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100352 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300353 Py_XSETREF(op->func_qualname, value);
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100354 return 0;
355}
356
357static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200358func_get_defaults(PyFunctionObject *op, void *Py_UNUSED(ignored))
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000359{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700360 if (PySys_Audit("object.__getattr__", "Os", op, "__defaults__") < 0) {
361 return NULL;
362 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 if (op->func_defaults == NULL) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200364 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 }
366 Py_INCREF(op->func_defaults);
367 return op->func_defaults;
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000368}
369
370static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200371func_set_defaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 /* Legal to del f.func_defaults.
374 * Can only set func_defaults to NULL or a tuple. */
375 if (value == Py_None)
376 value = NULL;
377 if (value != NULL && !PyTuple_Check(value)) {
378 PyErr_SetString(PyExc_TypeError,
379 "__defaults__ must be set to a tuple object");
380 return -1;
381 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700382 if (value) {
383 if (PySys_Audit("object.__setattr__", "OsO",
384 op, "__defaults__", value) < 0) {
385 return -1;
386 }
387 } else if (PySys_Audit("object.__delattr__", "Os",
388 op, "__defaults__") < 0) {
389 return -1;
390 }
391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 Py_XINCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300393 Py_XSETREF(op->func_defaults, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 return 0;
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000395}
396
Guido van Rossum4f72a782006-10-27 23:31:49 +0000397static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200398func_get_kwdefaults(PyFunctionObject *op, void *Py_UNUSED(ignored))
Guido van Rossum4f72a782006-10-27 23:31:49 +0000399{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700400 if (PySys_Audit("object.__getattr__", "Os",
401 op, "__kwdefaults__") < 0) {
402 return NULL;
403 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 if (op->func_kwdefaults == NULL) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200405 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 }
407 Py_INCREF(op->func_kwdefaults);
408 return op->func_kwdefaults;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000409}
410
411static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200412func_set_kwdefaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
Guido van Rossum4f72a782006-10-27 23:31:49 +0000413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (value == Py_None)
415 value = NULL;
416 /* Legal to del f.func_kwdefaults.
417 * Can only set func_kwdefaults to NULL or a dict. */
418 if (value != NULL && !PyDict_Check(value)) {
419 PyErr_SetString(PyExc_TypeError,
420 "__kwdefaults__ must be set to a dict object");
421 return -1;
422 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700423 if (value) {
424 if (PySys_Audit("object.__setattr__", "OsO",
425 op, "__kwdefaults__", value) < 0) {
426 return -1;
427 }
428 } else if (PySys_Audit("object.__delattr__", "Os",
429 op, "__kwdefaults__") < 0) {
430 return -1;
431 }
432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 Py_XINCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300434 Py_XSETREF(op->func_kwdefaults, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000436}
437
Neal Norwitzc1505362006-12-28 06:47:50 +0000438static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200439func_get_annotations(PyFunctionObject *op, void *Py_UNUSED(ignored))
Neal Norwitzc1505362006-12-28 06:47:50 +0000440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 if (op->func_annotations == NULL) {
442 op->func_annotations = PyDict_New();
443 if (op->func_annotations == NULL)
444 return NULL;
445 }
Yurii Karabas73019792020-11-25 12:43:18 +0200446 if (PyTuple_CheckExact(op->func_annotations)) {
447 PyObject *ann_tuple = op->func_annotations;
448 PyObject *ann_dict = PyDict_New();
449 if (ann_dict == NULL) {
450 return NULL;
451 }
452
453 assert(PyTuple_GET_SIZE(ann_tuple) % 2 == 0);
454
455 for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(ann_tuple); i += 2) {
456 int err = PyDict_SetItem(ann_dict,
457 PyTuple_GET_ITEM(ann_tuple, i),
458 PyTuple_GET_ITEM(ann_tuple, i + 1));
459
460 if (err < 0)
461 return NULL;
462 }
463 Py_SETREF(op->func_annotations, ann_dict);
464 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 Py_INCREF(op->func_annotations);
466 return op->func_annotations;
Neal Norwitzc1505362006-12-28 06:47:50 +0000467}
468
469static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200470func_set_annotations(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
Neal Norwitzc1505362006-12-28 06:47:50 +0000471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 if (value == Py_None)
473 value = NULL;
474 /* Legal to del f.func_annotations.
475 * Can only set func_annotations to NULL (through C api)
476 * or a dict. */
477 if (value != NULL && !PyDict_Check(value)) {
478 PyErr_SetString(PyExc_TypeError,
479 "__annotations__ must be set to a dict object");
480 return -1;
481 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 Py_XINCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300483 Py_XSETREF(op->func_annotations, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +0000485}
486
Guido van Rossum32d34c82001-09-20 21:45:26 +0000487static PyGetSetDef func_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 {"__code__", (getter)func_get_code, (setter)func_set_code},
489 {"__defaults__", (getter)func_get_defaults,
490 (setter)func_set_defaults},
491 {"__kwdefaults__", (getter)func_get_kwdefaults,
492 (setter)func_set_kwdefaults},
493 {"__annotations__", (getter)func_get_annotations,
494 (setter)func_set_annotations},
Benjamin Peterson23d7f122012-02-19 20:02:57 -0500495 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 {"__name__", (getter)func_get_name, (setter)func_set_name},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100497 {"__qualname__", (getter)func_get_qualname, (setter)func_set_qualname},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 {NULL} /* Sentinel */
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000499};
500
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200501/*[clinic input]
502class function "PyFunctionObject *" "&PyFunction_Type"
503[clinic start generated code]*/
504/*[clinic end generated code: output=da39a3ee5e6b4b0d input=70af9c90aa2e71b0]*/
Jeremy Hyltondf3f7932002-07-11 18:30:27 +0000505
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200506#include "clinic/funcobject.c.h"
507
508/* function.__new__() maintains the following invariants for closures.
509 The closure must correspond to the free variables of the code object.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510
511 if len(code.co_freevars) == 0:
512 closure = NULL
Jeremy Hyltondf3f7932002-07-11 18:30:27 +0000513 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 len(closure) == len(code.co_freevars)
Jeremy Hyltondf3f7932002-07-11 18:30:27 +0000515 for every elt in closure, type(elt) == cell
516*/
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000517
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200518/*[clinic input]
519@classmethod
520function.__new__ as func_new
521 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
522 a code object
523 globals: object(subclass_of="&PyDict_Type")
524 the globals dictionary
525 name: object = None
526 a string that overrides the name from the code object
527 argdefs as defaults: object = None
528 a tuple that specifies the default argument values
529 closure: object = None
530 a tuple that supplies the bindings for free variables
531
532Create a function object.
533[clinic start generated code]*/
534
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000535static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200536func_new_impl(PyTypeObject *type, PyCodeObject *code, PyObject *globals,
537 PyObject *name, PyObject *defaults, PyObject *closure)
538/*[clinic end generated code: output=99c6d9da3a24e3be input=93611752fc2daf11]*/
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 PyFunctionObject *newfunc;
541 Py_ssize_t nfree, nclosure;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 if (name != Py_None && !PyUnicode_Check(name)) {
544 PyErr_SetString(PyExc_TypeError,
545 "arg 3 (name) must be None or string");
546 return NULL;
547 }
548 if (defaults != Py_None && !PyTuple_Check(defaults)) {
549 PyErr_SetString(PyExc_TypeError,
550 "arg 4 (defaults) must be None or tuple");
551 return NULL;
552 }
553 nfree = PyTuple_GET_SIZE(code->co_freevars);
554 if (!PyTuple_Check(closure)) {
555 if (nfree && closure == Py_None) {
556 PyErr_SetString(PyExc_TypeError,
557 "arg 5 (closure) must be tuple");
558 return NULL;
559 }
560 else if (closure != Py_None) {
561 PyErr_SetString(PyExc_TypeError,
562 "arg 5 (closure) must be None or tuple");
563 return NULL;
564 }
565 }
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 /* check that the closure is well-formed */
568 nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
569 if (nfree != nclosure)
570 return PyErr_Format(PyExc_ValueError,
571 "%U requires closure of length %zd, not %zd",
572 code->co_name, nfree, nclosure);
573 if (nclosure) {
574 Py_ssize_t i;
575 for (i = 0; i < nclosure; i++) {
576 PyObject *o = PyTuple_GET_ITEM(closure, i);
577 if (!PyCell_Check(o)) {
578 return PyErr_Format(PyExc_TypeError,
579 "arg 5 (closure) expected cell, found %s",
Victor Stinner58ac7002020-02-07 03:04:21 +0100580 Py_TYPE(o)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 }
582 }
583 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700584 if (PySys_Audit("function.__new__", "O", code) < 0) {
585 return NULL;
586 }
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
589 globals);
Mark Shannon0332e562021-02-01 10:42:03 +0000590 if (newfunc == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 return NULL;
Mark Shannon0332e562021-02-01 10:42:03 +0000592 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 if (name != Py_None) {
594 Py_INCREF(name);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300595 Py_SETREF(newfunc->func_name, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 }
597 if (defaults != Py_None) {
598 Py_INCREF(defaults);
599 newfunc->func_defaults = defaults;
600 }
601 if (closure != Py_None) {
602 Py_INCREF(closure);
603 newfunc->func_closure = closure;
604 }
605
606 return (PyObject *)newfunc;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000607}
608
INADA Naoki3c452402018-07-04 11:15:50 +0900609static int
610func_clear(PyFunctionObject *op)
611{
612 Py_CLEAR(op->func_code);
613 Py_CLEAR(op->func_globals);
Mark Shannond6c33fb2021-01-29 13:24:55 +0000614 Py_CLEAR(op->func_builtins);
INADA Naoki3c452402018-07-04 11:15:50 +0900615 Py_CLEAR(op->func_name);
Mark Shannond6c33fb2021-01-29 13:24:55 +0000616 Py_CLEAR(op->func_qualname);
617 Py_CLEAR(op->func_module);
INADA Naoki3c452402018-07-04 11:15:50 +0900618 Py_CLEAR(op->func_defaults);
619 Py_CLEAR(op->func_kwdefaults);
620 Py_CLEAR(op->func_doc);
621 Py_CLEAR(op->func_dict);
622 Py_CLEAR(op->func_closure);
623 Py_CLEAR(op->func_annotations);
INADA Naoki3c452402018-07-04 11:15:50 +0900624 return 0;
625}
626
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000627static void
Fred Drakeee238b92000-07-09 06:03:25 +0000628func_dealloc(PyFunctionObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 _PyObject_GC_UNTRACK(op);
INADA Naoki3c452402018-07-04 11:15:50 +0900631 if (op->func_weakreflist != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 PyObject_ClearWeakRefs((PyObject *) op);
INADA Naoki3c452402018-07-04 11:15:50 +0900633 }
634 (void)func_clear(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 PyObject_GC_Del(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000636}
637
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000638static PyObject*
Fred Drakeee238b92000-07-09 06:03:25 +0000639func_repr(PyFunctionObject *op)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 return PyUnicode_FromFormat("<function %U at %p>",
Victor Stinner507a5742021-04-09 17:51:22 +0200642 op->func_qualname, op);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000643}
644
Guido van Rossum2e8f8a31993-11-05 10:20:10 +0000645static int
Jeremy Hylton8caad492000-06-23 14:18:11 +0000646func_traverse(PyFunctionObject *f, visitproc visit, void *arg)
647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 Py_VISIT(f->func_code);
649 Py_VISIT(f->func_globals);
Mark Shannond6c33fb2021-01-29 13:24:55 +0000650 Py_VISIT(f->func_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 Py_VISIT(f->func_module);
652 Py_VISIT(f->func_defaults);
653 Py_VISIT(f->func_kwdefaults);
654 Py_VISIT(f->func_doc);
655 Py_VISIT(f->func_name);
656 Py_VISIT(f->func_dict);
657 Py_VISIT(f->func_closure);
658 Py_VISIT(f->func_annotations);
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100659 Py_VISIT(f->func_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +0000661}
662
Tim Peters6d6c1a32001-08-02 04:15:00 +0000663/* Bind a function to an object */
664static PyObject *
665func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 if (obj == Py_None || obj == NULL) {
668 Py_INCREF(func);
669 return func;
670 }
671 return PyMethod_New(func, obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000672}
673
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000674PyTypeObject PyFunction_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 PyVarObject_HEAD_INIT(&PyType_Type, 0)
676 "function",
677 sizeof(PyFunctionObject),
678 0,
679 (destructor)func_dealloc, /* tp_dealloc */
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +0200680 offsetof(PyFunctionObject, vectorcall), /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 0, /* tp_getattr */
682 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200683 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 (reprfunc)func_repr, /* tp_repr */
685 0, /* tp_as_number */
686 0, /* tp_as_sequence */
687 0, /* tp_as_mapping */
688 0, /* tp_hash */
Jeroen Demeyer59543342019-06-18 13:05:41 +0200689 PyVectorcall_Call, /* tp_call */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 0, /* tp_str */
Benjamin Peterson2cf936f2012-02-19 01:16:13 -0500691 0, /* tp_getattro */
692 0, /* tp_setattro */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 0, /* tp_as_buffer */
Jeroen Demeyereb65e242019-05-28 14:42:53 +0200694 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Petr Viktorinffd97532020-02-11 17:46:57 +0100695 Py_TPFLAGS_HAVE_VECTORCALL |
Jeroen Demeyereb65e242019-05-28 14:42:53 +0200696 Py_TPFLAGS_METHOD_DESCRIPTOR, /* tp_flags */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200697 func_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 (traverseproc)func_traverse, /* tp_traverse */
INADA Naoki3c452402018-07-04 11:15:50 +0900699 (inquiry)func_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 0, /* tp_richcompare */
701 offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
702 0, /* tp_iter */
703 0, /* tp_iternext */
704 0, /* tp_methods */
705 func_memberlist, /* tp_members */
706 func_getsetlist, /* tp_getset */
707 0, /* tp_base */
708 0, /* tp_dict */
709 func_descr_get, /* tp_descr_get */
710 0, /* tp_descr_set */
711 offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */
712 0, /* tp_init */
713 0, /* tp_alloc */
714 func_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000715};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000716
717
Victor Stinner507a5742021-04-09 17:51:22 +0200718static int
719functools_copy_attr(PyObject *wrapper, PyObject *wrapped, PyObject *name)
720{
721 PyObject *value = PyObject_GetAttr(wrapped, name);
722 if (value == NULL) {
723 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
724 PyErr_Clear();
725 return 0;
726 }
727 return -1;
728 }
729
730 int res = PyObject_SetAttr(wrapper, name, value);
731 Py_DECREF(value);
732 return res;
733}
734
735// Similar to functools.wraps(wrapper, wrapped)
736static int
737functools_wraps(PyObject *wrapper, PyObject *wrapped)
738{
739#define COPY_ATTR(ATTR) \
740 do { \
741 _Py_IDENTIFIER(ATTR); \
742 PyObject *attr = _PyUnicode_FromId(&PyId_ ## ATTR); \
743 if (attr == NULL) { \
744 return -1; \
745 } \
746 if (functools_copy_attr(wrapper, wrapped, attr) < 0) { \
747 return -1; \
748 } \
749 } while (0) \
750
751 COPY_ATTR(__module__);
752 COPY_ATTR(__name__);
753 COPY_ATTR(__qualname__);
754 COPY_ATTR(__doc__);
755 COPY_ATTR(__annotations__);
756 return 0;
757
758#undef COPY_ATTR
759}
760
761
Tim Peters6d6c1a32001-08-02 04:15:00 +0000762/* Class method object */
763
764/* A class method receives the class as implicit first argument,
765 just like an instance method receives the instance.
766 To declare a class method, use this idiom:
767
768 class C:
Martin Panter6d57fe12016-09-17 03:26:16 +0000769 @classmethod
770 def f(cls, arg1, arg2, ...):
771 ...
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772
Tim Peters6d6c1a32001-08-02 04:15:00 +0000773 It can be called either on the class (e.g. C.f()) or on an instance
774 (e.g. C().f()); the instance is ignored except for its class.
775 If a class method is called for a derived class, the derived class
776 object is passed as the implied first argument.
777
778 Class methods are different than C++ or Java static methods.
779 If you want those, see static methods below.
780*/
781
782typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 PyObject_HEAD
784 PyObject *cm_callable;
Benjamin Peterson01d7eba2012-02-19 01:10:25 -0500785 PyObject *cm_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000786} classmethod;
787
788static void
789cm_dealloc(classmethod *cm)
790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 _PyObject_GC_UNTRACK((PyObject *)cm);
792 Py_XDECREF(cm->cm_callable);
Benjamin Peterson01d7eba2012-02-19 01:10:25 -0500793 Py_XDECREF(cm->cm_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 Py_TYPE(cm)->tp_free((PyObject *)cm);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000795}
796
Jeremy Hylton400d8ee2003-04-08 21:28:47 +0000797static int
798cm_traverse(classmethod *cm, visitproc visit, void *arg)
799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 Py_VISIT(cm->cm_callable);
Benjamin Peterson01d7eba2012-02-19 01:10:25 -0500801 Py_VISIT(cm->cm_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 return 0;
Jeremy Hylton400d8ee2003-04-08 21:28:47 +0000803}
804
805static int
806cm_clear(classmethod *cm)
807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 Py_CLEAR(cm->cm_callable);
Benjamin Peterson01d7eba2012-02-19 01:10:25 -0500809 Py_CLEAR(cm->cm_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 return 0;
Jeremy Hylton400d8ee2003-04-08 21:28:47 +0000811}
812
813
Tim Peters6d6c1a32001-08-02 04:15:00 +0000814static PyObject *
815cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 classmethod *cm = (classmethod *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 if (cm->cm_callable == NULL) {
820 PyErr_SetString(PyExc_RuntimeError,
821 "uninitialized classmethod object");
822 return NULL;
823 }
824 if (type == NULL)
825 type = (PyObject *)(Py_TYPE(obj));
Berker Peksag805f8f92019-08-25 01:37:25 +0300826 if (Py_TYPE(cm->cm_callable)->tp_descr_get != NULL) {
827 return Py_TYPE(cm->cm_callable)->tp_descr_get(cm->cm_callable, type,
828 NULL);
829 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 return PyMethod_New(cm->cm_callable, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000831}
832
833static int
834cm_init(PyObject *self, PyObject *args, PyObject *kwds)
835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 classmethod *cm = (classmethod *)self;
837 PyObject *callable;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 if (!_PyArg_NoKeywords("classmethod", kwds))
840 return -1;
Sylvain96480882017-07-09 05:45:06 +0200841 if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable))
842 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 Py_INCREF(callable);
Oren Milmand019bc82018-02-13 12:28:33 +0200844 Py_XSETREF(cm->cm_callable, callable);
Victor Stinner507a5742021-04-09 17:51:22 +0200845
846 if (functools_wraps((PyObject *)cm, cm->cm_callable) < 0) {
847 return -1;
848 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000850}
851
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000852static PyMemberDef cm_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY},
Victor Stinner507a5742021-04-09 17:51:22 +0200854 {"__wrapped__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 {NULL} /* Sentinel */
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000856};
857
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500858static PyObject *
859cm_get___isabstractmethod__(classmethod *cm, void *closure)
860{
861 int res = _PyObject_IsAbstract(cm->cm_callable);
862 if (res == -1) {
863 return NULL;
864 }
865 else if (res) {
866 Py_RETURN_TRUE;
867 }
868 Py_RETURN_FALSE;
869}
870
871static PyGetSetDef cm_getsetlist[] = {
872 {"__isabstractmethod__",
Victor Stinner507a5742021-04-09 17:51:22 +0200873 (getter)cm_get___isabstractmethod__, NULL, NULL, NULL},
Benjamin Peterson23d7f122012-02-19 20:02:57 -0500874 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500875 {NULL} /* Sentinel */
876};
877
Victor Stinner507a5742021-04-09 17:51:22 +0200878static PyObject*
879cm_repr(classmethod *cm)
880{
881 return PyUnicode_FromFormat("<classmethod(%R)>", cm->cm_callable);
882}
883
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000884PyDoc_STRVAR(classmethod_doc,
Guido van Rossum33c1a882001-12-17 02:53:53 +0000885"classmethod(function) -> method\n\
886\n\
887Convert a function to be a class method.\n\
888\n\
889A class method receives the class as implicit first argument,\n\
890just like an instance method receives the instance.\n\
891To declare a class method, use this idiom:\n\
892\n\
893 class C:\n\
Martin Panter6d57fe12016-09-17 03:26:16 +0000894 @classmethod\n\
895 def f(cls, arg1, arg2, ...):\n\
896 ...\n\
Guido van Rossum33c1a882001-12-17 02:53:53 +0000897\n\
898It can be called either on the class (e.g. C.f()) or on an instance\n\
899(e.g. C().f()). The instance is ignored except for its class.\n\
900If a class method is called for a derived class, the derived class\n\
901object is passed as the implied first argument.\n\
Sjoerd Mullender564980b2001-12-17 11:39:56 +0000902\n\
Guido van Rossum33c1a882001-12-17 02:53:53 +0000903Class methods are different than C++ or Java static methods.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000904If you want those, see the staticmethod builtin.");
Guido van Rossum33c1a882001-12-17 02:53:53 +0000905
Tim Peters6d6c1a32001-08-02 04:15:00 +0000906PyTypeObject PyClassMethod_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 PyVarObject_HEAD_INIT(&PyType_Type, 0)
908 "classmethod",
909 sizeof(classmethod),
910 0,
911 (destructor)cm_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200912 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 0, /* tp_getattr */
914 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200915 0, /* tp_as_async */
Victor Stinner507a5742021-04-09 17:51:22 +0200916 (reprfunc)cm_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 0, /* tp_as_number */
918 0, /* tp_as_sequence */
919 0, /* tp_as_mapping */
920 0, /* tp_hash */
921 0, /* tp_call */
922 0, /* tp_str */
Benjamin Peterson2cf936f2012-02-19 01:16:13 -0500923 0, /* tp_getattro */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 0, /* tp_setattro */
925 0, /* tp_as_buffer */
926 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
927 classmethod_doc, /* tp_doc */
928 (traverseproc)cm_traverse, /* tp_traverse */
929 (inquiry)cm_clear, /* tp_clear */
930 0, /* tp_richcompare */
931 0, /* tp_weaklistoffset */
932 0, /* tp_iter */
933 0, /* tp_iternext */
934 0, /* tp_methods */
935 cm_memberlist, /* tp_members */
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500936 cm_getsetlist, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 0, /* tp_base */
938 0, /* tp_dict */
939 cm_descr_get, /* tp_descr_get */
940 0, /* tp_descr_set */
Benjamin Peterson01d7eba2012-02-19 01:10:25 -0500941 offsetof(classmethod, cm_dict), /* tp_dictoffset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 cm_init, /* tp_init */
943 PyType_GenericAlloc, /* tp_alloc */
944 PyType_GenericNew, /* tp_new */
945 PyObject_GC_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000946};
947
948PyObject *
949PyClassMethod_New(PyObject *callable)
950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 classmethod *cm = (classmethod *)
952 PyType_GenericAlloc(&PyClassMethod_Type, 0);
953 if (cm != NULL) {
954 Py_INCREF(callable);
955 cm->cm_callable = callable;
956 }
957 return (PyObject *)cm;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000958}
959
960
961/* Static method object */
962
963/* A static method does not receive an implicit first argument.
964 To declare a static method, use this idiom:
965
966 class C:
Martin Panter6d57fe12016-09-17 03:26:16 +0000967 @staticmethod
968 def f(arg1, arg2, ...):
969 ...
Tim Peters6d6c1a32001-08-02 04:15:00 +0000970
971 It can be called either on the class (e.g. C.f()) or on an instance
Jess Shapiroe7eed782018-12-23 23:47:38 -0800972 (e.g. C().f()). Both the class and the instance are ignored, and
973 neither is passed implicitly as the first argument to the method.
Tim Peters6d6c1a32001-08-02 04:15:00 +0000974
975 Static methods in Python are similar to those found in Java or C++.
976 For a more advanced concept, see class methods above.
977*/
978
979typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 PyObject_HEAD
981 PyObject *sm_callable;
Benjamin Peterson01d7eba2012-02-19 01:10:25 -0500982 PyObject *sm_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000983} staticmethod;
984
985static void
986sm_dealloc(staticmethod *sm)
987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 _PyObject_GC_UNTRACK((PyObject *)sm);
989 Py_XDECREF(sm->sm_callable);
Benjamin Peterson01d7eba2012-02-19 01:10:25 -0500990 Py_XDECREF(sm->sm_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 Py_TYPE(sm)->tp_free((PyObject *)sm);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000992}
993
Jeremy Hylton400d8ee2003-04-08 21:28:47 +0000994static int
995sm_traverse(staticmethod *sm, visitproc visit, void *arg)
996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 Py_VISIT(sm->sm_callable);
Benjamin Peterson01d7eba2012-02-19 01:10:25 -0500998 Py_VISIT(sm->sm_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 return 0;
Jeremy Hylton400d8ee2003-04-08 21:28:47 +00001000}
1001
1002static int
1003sm_clear(staticmethod *sm)
1004{
Benjamin Peterson496c53d2012-02-19 01:11:56 -05001005 Py_CLEAR(sm->sm_callable);
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001006 Py_CLEAR(sm->sm_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 return 0;
Jeremy Hylton400d8ee2003-04-08 21:28:47 +00001008}
1009
Tim Peters6d6c1a32001-08-02 04:15:00 +00001010static PyObject *
1011sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
1012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 staticmethod *sm = (staticmethod *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 if (sm->sm_callable == NULL) {
1016 PyErr_SetString(PyExc_RuntimeError,
1017 "uninitialized staticmethod object");
1018 return NULL;
1019 }
1020 Py_INCREF(sm->sm_callable);
1021 return sm->sm_callable;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001022}
1023
1024static int
1025sm_init(PyObject *self, PyObject *args, PyObject *kwds)
1026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 staticmethod *sm = (staticmethod *)self;
1028 PyObject *callable;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 if (!_PyArg_NoKeywords("staticmethod", kwds))
1031 return -1;
Sylvain96480882017-07-09 05:45:06 +02001032 if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable))
1033 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 Py_INCREF(callable);
Oren Milmand019bc82018-02-13 12:28:33 +02001035 Py_XSETREF(sm->sm_callable, callable);
Victor Stinner507a5742021-04-09 17:51:22 +02001036
1037 if (functools_wraps((PyObject *)sm, sm->sm_callable) < 0) {
1038 return -1;
1039 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001041}
1042
Raymond Hettinger2bcde142009-05-29 04:52:27 +00001043static PyMemberDef sm_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY},
Victor Stinner507a5742021-04-09 17:51:22 +02001045 {"__wrapped__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 {NULL} /* Sentinel */
Raymond Hettinger2bcde142009-05-29 04:52:27 +00001047};
1048
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -05001049static PyObject *
1050sm_get___isabstractmethod__(staticmethod *sm, void *closure)
1051{
1052 int res = _PyObject_IsAbstract(sm->sm_callable);
1053 if (res == -1) {
1054 return NULL;
1055 }
1056 else if (res) {
1057 Py_RETURN_TRUE;
1058 }
1059 Py_RETURN_FALSE;
1060}
1061
1062static PyGetSetDef sm_getsetlist[] = {
1063 {"__isabstractmethod__",
Victor Stinner507a5742021-04-09 17:51:22 +02001064 (getter)sm_get___isabstractmethod__, NULL, NULL, NULL},
Benjamin Peterson23d7f122012-02-19 20:02:57 -05001065 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -05001066 {NULL} /* Sentinel */
1067};
1068
Victor Stinner507a5742021-04-09 17:51:22 +02001069static PyObject*
1070sm_repr(staticmethod *sm)
1071{
1072 return PyUnicode_FromFormat("<staticmethod(%R)>", sm->sm_callable);
1073}
1074
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001075PyDoc_STRVAR(staticmethod_doc,
Guido van Rossum33c1a882001-12-17 02:53:53 +00001076"staticmethod(function) -> method\n\
1077\n\
1078Convert a function to be a static method.\n\
1079\n\
1080A static method does not receive an implicit first argument.\n\
1081To declare a static method, use this idiom:\n\
1082\n\
1083 class C:\n\
Martin Panter6d57fe12016-09-17 03:26:16 +00001084 @staticmethod\n\
1085 def f(arg1, arg2, ...):\n\
1086 ...\n\
Guido van Rossum33c1a882001-12-17 02:53:53 +00001087\n\
1088It can be called either on the class (e.g. C.f()) or on an instance\n\
Jess Shapiroe7eed782018-12-23 23:47:38 -08001089(e.g. C().f()). Both the class and the instance are ignored, and\n\
1090neither is passed implicitly as the first argument to the method.\n\
Guido van Rossum33c1a882001-12-17 02:53:53 +00001091\n\
1092Static methods in Python are similar to those found in Java or C++.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001093For a more advanced concept, see the classmethod builtin.");
Guido van Rossum33c1a882001-12-17 02:53:53 +00001094
Tim Peters6d6c1a32001-08-02 04:15:00 +00001095PyTypeObject PyStaticMethod_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1097 "staticmethod",
1098 sizeof(staticmethod),
1099 0,
1100 (destructor)sm_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001101 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 0, /* tp_getattr */
1103 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001104 0, /* tp_as_async */
Victor Stinner507a5742021-04-09 17:51:22 +02001105 (reprfunc)sm_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 0, /* tp_as_number */
1107 0, /* tp_as_sequence */
1108 0, /* tp_as_mapping */
1109 0, /* tp_hash */
1110 0, /* tp_call */
1111 0, /* tp_str */
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001112 0, /* tp_getattro */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 0, /* tp_setattro */
1114 0, /* tp_as_buffer */
1115 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1116 staticmethod_doc, /* tp_doc */
1117 (traverseproc)sm_traverse, /* tp_traverse */
1118 (inquiry)sm_clear, /* tp_clear */
1119 0, /* tp_richcompare */
1120 0, /* tp_weaklistoffset */
1121 0, /* tp_iter */
1122 0, /* tp_iternext */
1123 0, /* tp_methods */
1124 sm_memberlist, /* tp_members */
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -05001125 sm_getsetlist, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 0, /* tp_base */
1127 0, /* tp_dict */
1128 sm_descr_get, /* tp_descr_get */
1129 0, /* tp_descr_set */
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001130 offsetof(staticmethod, sm_dict), /* tp_dictoffset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 sm_init, /* tp_init */
1132 PyType_GenericAlloc, /* tp_alloc */
1133 PyType_GenericNew, /* tp_new */
1134 PyObject_GC_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001135};
1136
1137PyObject *
1138PyStaticMethod_New(PyObject *callable)
1139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 staticmethod *sm = (staticmethod *)
1141 PyType_GenericAlloc(&PyStaticMethod_Type, 0);
1142 if (sm != NULL) {
1143 Py_INCREF(callable);
1144 sm->sm_callable = callable;
1145 }
1146 return (PyObject *)sm;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001147}