1
2 /* Function object implementation */
3
4 #include "Python.h"
5 #include "pycore_object.h"
6 #include "pycore_tupleobject.h"
7 #include "code.h"
8 #include "structmember.h" // PyMemberDef
9
10 PyObject *
PyFunction_NewWithQualName(PyObject * code,PyObject * globals,PyObject * qualname)11 PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
12 {
13 PyFunctionObject *op;
14 PyObject *doc, *consts, *module;
15 static PyObject *__name__ = NULL;
16
17 if (__name__ == NULL) {
18 __name__ = PyUnicode_InternFromString("__name__");
19 if (__name__ == NULL)
20 return NULL;
21 }
22
23 /* __module__: If module name is in globals, use it.
24 Otherwise, use None. */
25 module = PyDict_GetItemWithError(globals, __name__);
26 if (module) {
27 Py_INCREF(module);
28 }
29 else if (PyErr_Occurred()) {
30 return NULL;
31 }
32
33 op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
34 if (op == NULL) {
35 Py_XDECREF(module);
36 return NULL;
37 }
38 /* Note: No failures from this point on, since func_dealloc() does not
39 expect a partially-created object. */
40
41 op->func_weakreflist = NULL;
42 Py_INCREF(code);
43 op->func_code = code;
44 Py_INCREF(globals);
45 op->func_globals = globals;
46 op->func_name = ((PyCodeObject *)code)->co_name;
47 Py_INCREF(op->func_name);
48 op->func_defaults = NULL; /* No default arguments */
49 op->func_kwdefaults = NULL; /* No keyword only defaults */
50 op->func_closure = NULL;
51 op->vectorcall = _PyFunction_Vectorcall;
52 op->func_module = module;
53
54 consts = ((PyCodeObject *)code)->co_consts;
55 if (PyTuple_Size(consts) >= 1) {
56 doc = PyTuple_GetItem(consts, 0);
57 if (!PyUnicode_Check(doc))
58 doc = Py_None;
59 }
60 else
61 doc = Py_None;
62 Py_INCREF(doc);
63 op->func_doc = doc;
64
65 op->func_dict = NULL;
66 op->func_annotations = NULL;
67
68 if (qualname)
69 op->func_qualname = qualname;
70 else
71 op->func_qualname = op->func_name;
72 Py_INCREF(op->func_qualname);
73
74 _PyObject_GC_TRACK(op);
75 return (PyObject *)op;
76 }
77
78 PyObject *
PyFunction_New(PyObject * code,PyObject * globals)79 PyFunction_New(PyObject *code, PyObject *globals)
80 {
81 return PyFunction_NewWithQualName(code, globals, NULL);
82 }
83
84 PyObject *
PyFunction_GetCode(PyObject * op)85 PyFunction_GetCode(PyObject *op)
86 {
87 if (!PyFunction_Check(op)) {
88 PyErr_BadInternalCall();
89 return NULL;
90 }
91 return ((PyFunctionObject *) op) -> func_code;
92 }
93
94 PyObject *
PyFunction_GetGlobals(PyObject * op)95 PyFunction_GetGlobals(PyObject *op)
96 {
97 if (!PyFunction_Check(op)) {
98 PyErr_BadInternalCall();
99 return NULL;
100 }
101 return ((PyFunctionObject *) op) -> func_globals;
102 }
103
104 PyObject *
PyFunction_GetModule(PyObject * op)105 PyFunction_GetModule(PyObject *op)
106 {
107 if (!PyFunction_Check(op)) {
108 PyErr_BadInternalCall();
109 return NULL;
110 }
111 return ((PyFunctionObject *) op) -> func_module;
112 }
113
114 PyObject *
PyFunction_GetDefaults(PyObject * op)115 PyFunction_GetDefaults(PyObject *op)
116 {
117 if (!PyFunction_Check(op)) {
118 PyErr_BadInternalCall();
119 return NULL;
120 }
121 return ((PyFunctionObject *) op) -> func_defaults;
122 }
123
124 int
PyFunction_SetDefaults(PyObject * op,PyObject * defaults)125 PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
126 {
127 if (!PyFunction_Check(op)) {
128 PyErr_BadInternalCall();
129 return -1;
130 }
131 if (defaults == Py_None)
132 defaults = NULL;
133 else if (defaults && PyTuple_Check(defaults)) {
134 Py_INCREF(defaults);
135 }
136 else {
137 PyErr_SetString(PyExc_SystemError, "non-tuple default args");
138 return -1;
139 }
140 Py_XSETREF(((PyFunctionObject *)op)->func_defaults, defaults);
141 return 0;
142 }
143
144 PyObject *
PyFunction_GetKwDefaults(PyObject * op)145 PyFunction_GetKwDefaults(PyObject *op)
146 {
147 if (!PyFunction_Check(op)) {
148 PyErr_BadInternalCall();
149 return NULL;
150 }
151 return ((PyFunctionObject *) op) -> func_kwdefaults;
152 }
153
154 int
PyFunction_SetKwDefaults(PyObject * op,PyObject * defaults)155 PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults)
156 {
157 if (!PyFunction_Check(op)) {
158 PyErr_BadInternalCall();
159 return -1;
160 }
161 if (defaults == Py_None)
162 defaults = NULL;
163 else if (defaults && PyDict_Check(defaults)) {
164 Py_INCREF(defaults);
165 }
166 else {
167 PyErr_SetString(PyExc_SystemError,
168 "non-dict keyword only default args");
169 return -1;
170 }
171 Py_XSETREF(((PyFunctionObject *)op)->func_kwdefaults, defaults);
172 return 0;
173 }
174
175 PyObject *
PyFunction_GetClosure(PyObject * op)176 PyFunction_GetClosure(PyObject *op)
177 {
178 if (!PyFunction_Check(op)) {
179 PyErr_BadInternalCall();
180 return NULL;
181 }
182 return ((PyFunctionObject *) op) -> func_closure;
183 }
184
185 int
PyFunction_SetClosure(PyObject * op,PyObject * closure)186 PyFunction_SetClosure(PyObject *op, PyObject *closure)
187 {
188 if (!PyFunction_Check(op)) {
189 PyErr_BadInternalCall();
190 return -1;
191 }
192 if (closure == Py_None)
193 closure = NULL;
194 else if (PyTuple_Check(closure)) {
195 Py_INCREF(closure);
196 }
197 else {
198 PyErr_Format(PyExc_SystemError,
199 "expected tuple for closure, got '%.100s'",
200 Py_TYPE(closure)->tp_name);
201 return -1;
202 }
203 Py_XSETREF(((PyFunctionObject *)op)->func_closure, closure);
204 return 0;
205 }
206
207 PyObject *
PyFunction_GetAnnotations(PyObject * op)208 PyFunction_GetAnnotations(PyObject *op)
209 {
210 if (!PyFunction_Check(op)) {
211 PyErr_BadInternalCall();
212 return NULL;
213 }
214 return ((PyFunctionObject *) op) -> func_annotations;
215 }
216
217 int
PyFunction_SetAnnotations(PyObject * op,PyObject * annotations)218 PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)
219 {
220 if (!PyFunction_Check(op)) {
221 PyErr_BadInternalCall();
222 return -1;
223 }
224 if (annotations == Py_None)
225 annotations = NULL;
226 else if (annotations && PyDict_Check(annotations)) {
227 Py_INCREF(annotations);
228 }
229 else {
230 PyErr_SetString(PyExc_SystemError,
231 "non-dict annotations");
232 return -1;
233 }
234 Py_XSETREF(((PyFunctionObject *)op)->func_annotations, annotations);
235 return 0;
236 }
237
238 /* Methods */
239
240 #define OFF(x) offsetof(PyFunctionObject, x)
241
242 static PyMemberDef func_memberlist[] = {
243 {"__closure__", T_OBJECT, OFF(func_closure), READONLY},
244 {"__doc__", T_OBJECT, OFF(func_doc), 0},
245 {"__globals__", T_OBJECT, OFF(func_globals), READONLY},
246 {"__module__", T_OBJECT, OFF(func_module), 0},
247 {NULL} /* Sentinel */
248 };
249
250 static PyObject *
func_get_code(PyFunctionObject * op,void * Py_UNUSED (ignored))251 func_get_code(PyFunctionObject *op, void *Py_UNUSED(ignored))
252 {
253 if (PySys_Audit("object.__getattr__", "Os", op, "__code__") < 0) {
254 return NULL;
255 }
256
257 Py_INCREF(op->func_code);
258 return op->func_code;
259 }
260
261 static int
func_set_code(PyFunctionObject * op,PyObject * value,void * Py_UNUSED (ignored))262 func_set_code(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
263 {
264 Py_ssize_t nfree, nclosure;
265
266 /* Not legal to del f.func_code or to set it to anything
267 * other than a code object. */
268 if (value == NULL || !PyCode_Check(value)) {
269 PyErr_SetString(PyExc_TypeError,
270 "__code__ must be set to a code object");
271 return -1;
272 }
273
274 if (PySys_Audit("object.__setattr__", "OsO",
275 op, "__code__", value) < 0) {
276 return -1;
277 }
278
279 nfree = PyCode_GetNumFree((PyCodeObject *)value);
280 nclosure = (op->func_closure == NULL ? 0 :
281 PyTuple_GET_SIZE(op->func_closure));
282 if (nclosure != nfree) {
283 PyErr_Format(PyExc_ValueError,
284 "%U() requires a code object with %zd free vars,"
285 " not %zd",
286 op->func_name,
287 nclosure, nfree);
288 return -1;
289 }
290 Py_INCREF(value);
291 Py_XSETREF(op->func_code, value);
292 return 0;
293 }
294
295 static PyObject *
func_get_name(PyFunctionObject * op,void * Py_UNUSED (ignored))296 func_get_name(PyFunctionObject *op, void *Py_UNUSED(ignored))
297 {
298 Py_INCREF(op->func_name);
299 return op->func_name;
300 }
301
302 static int
func_set_name(PyFunctionObject * op,PyObject * value,void * Py_UNUSED (ignored))303 func_set_name(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
304 {
305 /* Not legal to del f.func_name or to set it to anything
306 * other than a string object. */
307 if (value == NULL || !PyUnicode_Check(value)) {
308 PyErr_SetString(PyExc_TypeError,
309 "__name__ must be set to a string object");
310 return -1;
311 }
312 Py_INCREF(value);
313 Py_XSETREF(op->func_name, value);
314 return 0;
315 }
316
317 static PyObject *
func_get_qualname(PyFunctionObject * op,void * Py_UNUSED (ignored))318 func_get_qualname(PyFunctionObject *op, void *Py_UNUSED(ignored))
319 {
320 Py_INCREF(op->func_qualname);
321 return op->func_qualname;
322 }
323
324 static int
func_set_qualname(PyFunctionObject * op,PyObject * value,void * Py_UNUSED (ignored))325 func_set_qualname(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
326 {
327 /* Not legal to del f.__qualname__ or to set it to anything
328 * other than a string object. */
329 if (value == NULL || !PyUnicode_Check(value)) {
330 PyErr_SetString(PyExc_TypeError,
331 "__qualname__ must be set to a string object");
332 return -1;
333 }
334 Py_INCREF(value);
335 Py_XSETREF(op->func_qualname, value);
336 return 0;
337 }
338
339 static PyObject *
func_get_defaults(PyFunctionObject * op,void * Py_UNUSED (ignored))340 func_get_defaults(PyFunctionObject *op, void *Py_UNUSED(ignored))
341 {
342 if (PySys_Audit("object.__getattr__", "Os", op, "__defaults__") < 0) {
343 return NULL;
344 }
345 if (op->func_defaults == NULL) {
346 Py_RETURN_NONE;
347 }
348 Py_INCREF(op->func_defaults);
349 return op->func_defaults;
350 }
351
352 static int
func_set_defaults(PyFunctionObject * op,PyObject * value,void * Py_UNUSED (ignored))353 func_set_defaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
354 {
355 /* Legal to del f.func_defaults.
356 * Can only set func_defaults to NULL or a tuple. */
357 if (value == Py_None)
358 value = NULL;
359 if (value != NULL && !PyTuple_Check(value)) {
360 PyErr_SetString(PyExc_TypeError,
361 "__defaults__ must be set to a tuple object");
362 return -1;
363 }
364 if (value) {
365 if (PySys_Audit("object.__setattr__", "OsO",
366 op, "__defaults__", value) < 0) {
367 return -1;
368 }
369 } else if (PySys_Audit("object.__delattr__", "Os",
370 op, "__defaults__") < 0) {
371 return -1;
372 }
373
374 Py_XINCREF(value);
375 Py_XSETREF(op->func_defaults, value);
376 return 0;
377 }
378
379 static PyObject *
func_get_kwdefaults(PyFunctionObject * op,void * Py_UNUSED (ignored))380 func_get_kwdefaults(PyFunctionObject *op, void *Py_UNUSED(ignored))
381 {
382 if (PySys_Audit("object.__getattr__", "Os",
383 op, "__kwdefaults__") < 0) {
384 return NULL;
385 }
386 if (op->func_kwdefaults == NULL) {
387 Py_RETURN_NONE;
388 }
389 Py_INCREF(op->func_kwdefaults);
390 return op->func_kwdefaults;
391 }
392
393 static int
func_set_kwdefaults(PyFunctionObject * op,PyObject * value,void * Py_UNUSED (ignored))394 func_set_kwdefaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
395 {
396 if (value == Py_None)
397 value = NULL;
398 /* Legal to del f.func_kwdefaults.
399 * Can only set func_kwdefaults to NULL or a dict. */
400 if (value != NULL && !PyDict_Check(value)) {
401 PyErr_SetString(PyExc_TypeError,
402 "__kwdefaults__ must be set to a dict object");
403 return -1;
404 }
405 if (value) {
406 if (PySys_Audit("object.__setattr__", "OsO",
407 op, "__kwdefaults__", value) < 0) {
408 return -1;
409 }
410 } else if (PySys_Audit("object.__delattr__", "Os",
411 op, "__kwdefaults__") < 0) {
412 return -1;
413 }
414
415 Py_XINCREF(value);
416 Py_XSETREF(op->func_kwdefaults, value);
417 return 0;
418 }
419
420 static PyObject *
func_get_annotations(PyFunctionObject * op,void * Py_UNUSED (ignored))421 func_get_annotations(PyFunctionObject *op, void *Py_UNUSED(ignored))
422 {
423 if (op->func_annotations == NULL) {
424 op->func_annotations = PyDict_New();
425 if (op->func_annotations == NULL)
426 return NULL;
427 }
428 Py_INCREF(op->func_annotations);
429 return op->func_annotations;
430 }
431
432 static int
func_set_annotations(PyFunctionObject * op,PyObject * value,void * Py_UNUSED (ignored))433 func_set_annotations(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
434 {
435 if (value == Py_None)
436 value = NULL;
437 /* Legal to del f.func_annotations.
438 * Can only set func_annotations to NULL (through C api)
439 * or a dict. */
440 if (value != NULL && !PyDict_Check(value)) {
441 PyErr_SetString(PyExc_TypeError,
442 "__annotations__ must be set to a dict object");
443 return -1;
444 }
445 Py_XINCREF(value);
446 Py_XSETREF(op->func_annotations, value);
447 return 0;
448 }
449
450 static PyGetSetDef func_getsetlist[] = {
451 {"__code__", (getter)func_get_code, (setter)func_set_code},
452 {"__defaults__", (getter)func_get_defaults,
453 (setter)func_set_defaults},
454 {"__kwdefaults__", (getter)func_get_kwdefaults,
455 (setter)func_set_kwdefaults},
456 {"__annotations__", (getter)func_get_annotations,
457 (setter)func_set_annotations},
458 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
459 {"__name__", (getter)func_get_name, (setter)func_set_name},
460 {"__qualname__", (getter)func_get_qualname, (setter)func_set_qualname},
461 {NULL} /* Sentinel */
462 };
463
464 /*[clinic input]
465 class function "PyFunctionObject *" "&PyFunction_Type"
466 [clinic start generated code]*/
467 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=70af9c90aa2e71b0]*/
468
469 #include "clinic/funcobject.c.h"
470
471 /* function.__new__() maintains the following invariants for closures.
472 The closure must correspond to the free variables of the code object.
473
474 if len(code.co_freevars) == 0:
475 closure = NULL
476 else:
477 len(closure) == len(code.co_freevars)
478 for every elt in closure, type(elt) == cell
479 */
480
481 /*[clinic input]
482 @classmethod
483 function.__new__ as func_new
484 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
485 a code object
486 globals: object(subclass_of="&PyDict_Type")
487 the globals dictionary
488 name: object = None
489 a string that overrides the name from the code object
490 argdefs as defaults: object = None
491 a tuple that specifies the default argument values
492 closure: object = None
493 a tuple that supplies the bindings for free variables
494
495 Create a function object.
496 [clinic start generated code]*/
497
498 static PyObject *
func_new_impl(PyTypeObject * type,PyCodeObject * code,PyObject * globals,PyObject * name,PyObject * defaults,PyObject * closure)499 func_new_impl(PyTypeObject *type, PyCodeObject *code, PyObject *globals,
500 PyObject *name, PyObject *defaults, PyObject *closure)
501 /*[clinic end generated code: output=99c6d9da3a24e3be input=93611752fc2daf11]*/
502 {
503 PyFunctionObject *newfunc;
504 Py_ssize_t nfree, nclosure;
505
506 if (name != Py_None && !PyUnicode_Check(name)) {
507 PyErr_SetString(PyExc_TypeError,
508 "arg 3 (name) must be None or string");
509 return NULL;
510 }
511 if (defaults != Py_None && !PyTuple_Check(defaults)) {
512 PyErr_SetString(PyExc_TypeError,
513 "arg 4 (defaults) must be None or tuple");
514 return NULL;
515 }
516 nfree = PyTuple_GET_SIZE(code->co_freevars);
517 if (!PyTuple_Check(closure)) {
518 if (nfree && closure == Py_None) {
519 PyErr_SetString(PyExc_TypeError,
520 "arg 5 (closure) must be tuple");
521 return NULL;
522 }
523 else if (closure != Py_None) {
524 PyErr_SetString(PyExc_TypeError,
525 "arg 5 (closure) must be None or tuple");
526 return NULL;
527 }
528 }
529
530 /* check that the closure is well-formed */
531 nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
532 if (nfree != nclosure)
533 return PyErr_Format(PyExc_ValueError,
534 "%U requires closure of length %zd, not %zd",
535 code->co_name, nfree, nclosure);
536 if (nclosure) {
537 Py_ssize_t i;
538 for (i = 0; i < nclosure; i++) {
539 PyObject *o = PyTuple_GET_ITEM(closure, i);
540 if (!PyCell_Check(o)) {
541 return PyErr_Format(PyExc_TypeError,
542 "arg 5 (closure) expected cell, found %s",
543 Py_TYPE(o)->tp_name);
544 }
545 }
546 }
547 if (PySys_Audit("function.__new__", "O", code) < 0) {
548 return NULL;
549 }
550
551 newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
552 globals);
553 if (newfunc == NULL)
554 return NULL;
555
556 if (name != Py_None) {
557 Py_INCREF(name);
558 Py_SETREF(newfunc->func_name, name);
559 }
560 if (defaults != Py_None) {
561 Py_INCREF(defaults);
562 newfunc->func_defaults = defaults;
563 }
564 if (closure != Py_None) {
565 Py_INCREF(closure);
566 newfunc->func_closure = closure;
567 }
568
569 return (PyObject *)newfunc;
570 }
571
572 static int
func_clear(PyFunctionObject * op)573 func_clear(PyFunctionObject *op)
574 {
575 Py_CLEAR(op->func_code);
576 Py_CLEAR(op->func_globals);
577 Py_CLEAR(op->func_module);
578 Py_CLEAR(op->func_name);
579 Py_CLEAR(op->func_defaults);
580 Py_CLEAR(op->func_kwdefaults);
581 Py_CLEAR(op->func_doc);
582 Py_CLEAR(op->func_dict);
583 Py_CLEAR(op->func_closure);
584 Py_CLEAR(op->func_annotations);
585 Py_CLEAR(op->func_qualname);
586 return 0;
587 }
588
589 static void
func_dealloc(PyFunctionObject * op)590 func_dealloc(PyFunctionObject *op)
591 {
592 _PyObject_GC_UNTRACK(op);
593 if (op->func_weakreflist != NULL) {
594 PyObject_ClearWeakRefs((PyObject *) op);
595 }
596 (void)func_clear(op);
597 PyObject_GC_Del(op);
598 }
599
600 static PyObject*
func_repr(PyFunctionObject * op)601 func_repr(PyFunctionObject *op)
602 {
603 return PyUnicode_FromFormat("<function %U at %p>",
604 op->func_qualname, op);
605 }
606
607 static int
func_traverse(PyFunctionObject * f,visitproc visit,void * arg)608 func_traverse(PyFunctionObject *f, visitproc visit, void *arg)
609 {
610 Py_VISIT(f->func_code);
611 Py_VISIT(f->func_globals);
612 Py_VISIT(f->func_module);
613 Py_VISIT(f->func_defaults);
614 Py_VISIT(f->func_kwdefaults);
615 Py_VISIT(f->func_doc);
616 Py_VISIT(f->func_name);
617 Py_VISIT(f->func_dict);
618 Py_VISIT(f->func_closure);
619 Py_VISIT(f->func_annotations);
620 Py_VISIT(f->func_qualname);
621 return 0;
622 }
623
624 /* Bind a function to an object */
625 static PyObject *
func_descr_get(PyObject * func,PyObject * obj,PyObject * type)626 func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
627 {
628 if (obj == Py_None || obj == NULL) {
629 Py_INCREF(func);
630 return func;
631 }
632 return PyMethod_New(func, obj);
633 }
634
635 PyTypeObject PyFunction_Type = {
636 PyVarObject_HEAD_INIT(&PyType_Type, 0)
637 "function",
638 sizeof(PyFunctionObject),
639 0,
640 (destructor)func_dealloc, /* tp_dealloc */
641 offsetof(PyFunctionObject, vectorcall), /* tp_vectorcall_offset */
642 0, /* tp_getattr */
643 0, /* tp_setattr */
644 0, /* tp_as_async */
645 (reprfunc)func_repr, /* tp_repr */
646 0, /* tp_as_number */
647 0, /* tp_as_sequence */
648 0, /* tp_as_mapping */
649 0, /* tp_hash */
650 PyVectorcall_Call, /* tp_call */
651 0, /* tp_str */
652 0, /* tp_getattro */
653 0, /* tp_setattro */
654 0, /* tp_as_buffer */
655 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
656 Py_TPFLAGS_HAVE_VECTORCALL |
657 Py_TPFLAGS_METHOD_DESCRIPTOR, /* tp_flags */
658 func_new__doc__, /* tp_doc */
659 (traverseproc)func_traverse, /* tp_traverse */
660 (inquiry)func_clear, /* tp_clear */
661 0, /* tp_richcompare */
662 offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
663 0, /* tp_iter */
664 0, /* tp_iternext */
665 0, /* tp_methods */
666 func_memberlist, /* tp_members */
667 func_getsetlist, /* tp_getset */
668 0, /* tp_base */
669 0, /* tp_dict */
670 func_descr_get, /* tp_descr_get */
671 0, /* tp_descr_set */
672 offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */
673 0, /* tp_init */
674 0, /* tp_alloc */
675 func_new, /* tp_new */
676 };
677
678
679 /* Class method object */
680
681 /* A class method receives the class as implicit first argument,
682 just like an instance method receives the instance.
683 To declare a class method, use this idiom:
684
685 class C:
686 @classmethod
687 def f(cls, arg1, arg2, ...):
688 ...
689
690 It can be called either on the class (e.g. C.f()) or on an instance
691 (e.g. C().f()); the instance is ignored except for its class.
692 If a class method is called for a derived class, the derived class
693 object is passed as the implied first argument.
694
695 Class methods are different than C++ or Java static methods.
696 If you want those, see static methods below.
697 */
698
699 typedef struct {
700 PyObject_HEAD
701 PyObject *cm_callable;
702 PyObject *cm_dict;
703 } classmethod;
704
705 static void
cm_dealloc(classmethod * cm)706 cm_dealloc(classmethod *cm)
707 {
708 _PyObject_GC_UNTRACK((PyObject *)cm);
709 Py_XDECREF(cm->cm_callable);
710 Py_XDECREF(cm->cm_dict);
711 Py_TYPE(cm)->tp_free((PyObject *)cm);
712 }
713
714 static int
cm_traverse(classmethod * cm,visitproc visit,void * arg)715 cm_traverse(classmethod *cm, visitproc visit, void *arg)
716 {
717 Py_VISIT(cm->cm_callable);
718 Py_VISIT(cm->cm_dict);
719 return 0;
720 }
721
722 static int
cm_clear(classmethod * cm)723 cm_clear(classmethod *cm)
724 {
725 Py_CLEAR(cm->cm_callable);
726 Py_CLEAR(cm->cm_dict);
727 return 0;
728 }
729
730
731 static PyObject *
cm_descr_get(PyObject * self,PyObject * obj,PyObject * type)732 cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
733 {
734 classmethod *cm = (classmethod *)self;
735
736 if (cm->cm_callable == NULL) {
737 PyErr_SetString(PyExc_RuntimeError,
738 "uninitialized classmethod object");
739 return NULL;
740 }
741 if (type == NULL)
742 type = (PyObject *)(Py_TYPE(obj));
743 if (Py_TYPE(cm->cm_callable)->tp_descr_get != NULL) {
744 return Py_TYPE(cm->cm_callable)->tp_descr_get(cm->cm_callable, type,
745 NULL);
746 }
747 return PyMethod_New(cm->cm_callable, type);
748 }
749
750 static int
cm_init(PyObject * self,PyObject * args,PyObject * kwds)751 cm_init(PyObject *self, PyObject *args, PyObject *kwds)
752 {
753 classmethod *cm = (classmethod *)self;
754 PyObject *callable;
755
756 if (!_PyArg_NoKeywords("classmethod", kwds))
757 return -1;
758 if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable))
759 return -1;
760 Py_INCREF(callable);
761 Py_XSETREF(cm->cm_callable, callable);
762 return 0;
763 }
764
765 static PyMemberDef cm_memberlist[] = {
766 {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY},
767 {NULL} /* Sentinel */
768 };
769
770 static PyObject *
cm_get___isabstractmethod__(classmethod * cm,void * closure)771 cm_get___isabstractmethod__(classmethod *cm, void *closure)
772 {
773 int res = _PyObject_IsAbstract(cm->cm_callable);
774 if (res == -1) {
775 return NULL;
776 }
777 else if (res) {
778 Py_RETURN_TRUE;
779 }
780 Py_RETURN_FALSE;
781 }
782
783 static PyGetSetDef cm_getsetlist[] = {
784 {"__isabstractmethod__",
785 (getter)cm_get___isabstractmethod__, NULL,
786 NULL,
787 NULL},
788 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
789 {NULL} /* Sentinel */
790 };
791
792 PyDoc_STRVAR(classmethod_doc,
793 "classmethod(function) -> method\n\
794 \n\
795 Convert a function to be a class method.\n\
796 \n\
797 A class method receives the class as implicit first argument,\n\
798 just like an instance method receives the instance.\n\
799 To declare a class method, use this idiom:\n\
800 \n\
801 class C:\n\
802 @classmethod\n\
803 def f(cls, arg1, arg2, ...):\n\
804 ...\n\
805 \n\
806 It can be called either on the class (e.g. C.f()) or on an instance\n\
807 (e.g. C().f()). The instance is ignored except for its class.\n\
808 If a class method is called for a derived class, the derived class\n\
809 object is passed as the implied first argument.\n\
810 \n\
811 Class methods are different than C++ or Java static methods.\n\
812 If you want those, see the staticmethod builtin.");
813
814 PyTypeObject PyClassMethod_Type = {
815 PyVarObject_HEAD_INIT(&PyType_Type, 0)
816 "classmethod",
817 sizeof(classmethod),
818 0,
819 (destructor)cm_dealloc, /* tp_dealloc */
820 0, /* tp_vectorcall_offset */
821 0, /* tp_getattr */
822 0, /* tp_setattr */
823 0, /* tp_as_async */
824 0, /* tp_repr */
825 0, /* tp_as_number */
826 0, /* tp_as_sequence */
827 0, /* tp_as_mapping */
828 0, /* tp_hash */
829 0, /* tp_call */
830 0, /* tp_str */
831 0, /* tp_getattro */
832 0, /* tp_setattro */
833 0, /* tp_as_buffer */
834 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
835 classmethod_doc, /* tp_doc */
836 (traverseproc)cm_traverse, /* tp_traverse */
837 (inquiry)cm_clear, /* tp_clear */
838 0, /* tp_richcompare */
839 0, /* tp_weaklistoffset */
840 0, /* tp_iter */
841 0, /* tp_iternext */
842 0, /* tp_methods */
843 cm_memberlist, /* tp_members */
844 cm_getsetlist, /* tp_getset */
845 0, /* tp_base */
846 0, /* tp_dict */
847 cm_descr_get, /* tp_descr_get */
848 0, /* tp_descr_set */
849 offsetof(classmethod, cm_dict), /* tp_dictoffset */
850 cm_init, /* tp_init */
851 PyType_GenericAlloc, /* tp_alloc */
852 PyType_GenericNew, /* tp_new */
853 PyObject_GC_Del, /* tp_free */
854 };
855
856 PyObject *
PyClassMethod_New(PyObject * callable)857 PyClassMethod_New(PyObject *callable)
858 {
859 classmethod *cm = (classmethod *)
860 PyType_GenericAlloc(&PyClassMethod_Type, 0);
861 if (cm != NULL) {
862 Py_INCREF(callable);
863 cm->cm_callable = callable;
864 }
865 return (PyObject *)cm;
866 }
867
868
869 /* Static method object */
870
871 /* A static method does not receive an implicit first argument.
872 To declare a static method, use this idiom:
873
874 class C:
875 @staticmethod
876 def f(arg1, arg2, ...):
877 ...
878
879 It can be called either on the class (e.g. C.f()) or on an instance
880 (e.g. C().f()). Both the class and the instance are ignored, and
881 neither is passed implicitly as the first argument to the method.
882
883 Static methods in Python are similar to those found in Java or C++.
884 For a more advanced concept, see class methods above.
885 */
886
887 typedef struct {
888 PyObject_HEAD
889 PyObject *sm_callable;
890 PyObject *sm_dict;
891 } staticmethod;
892
893 static void
sm_dealloc(staticmethod * sm)894 sm_dealloc(staticmethod *sm)
895 {
896 _PyObject_GC_UNTRACK((PyObject *)sm);
897 Py_XDECREF(sm->sm_callable);
898 Py_XDECREF(sm->sm_dict);
899 Py_TYPE(sm)->tp_free((PyObject *)sm);
900 }
901
902 static int
sm_traverse(staticmethod * sm,visitproc visit,void * arg)903 sm_traverse(staticmethod *sm, visitproc visit, void *arg)
904 {
905 Py_VISIT(sm->sm_callable);
906 Py_VISIT(sm->sm_dict);
907 return 0;
908 }
909
910 static int
sm_clear(staticmethod * sm)911 sm_clear(staticmethod *sm)
912 {
913 Py_CLEAR(sm->sm_callable);
914 Py_CLEAR(sm->sm_dict);
915 return 0;
916 }
917
918 static PyObject *
sm_descr_get(PyObject * self,PyObject * obj,PyObject * type)919 sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
920 {
921 staticmethod *sm = (staticmethod *)self;
922
923 if (sm->sm_callable == NULL) {
924 PyErr_SetString(PyExc_RuntimeError,
925 "uninitialized staticmethod object");
926 return NULL;
927 }
928 Py_INCREF(sm->sm_callable);
929 return sm->sm_callable;
930 }
931
932 static int
sm_init(PyObject * self,PyObject * args,PyObject * kwds)933 sm_init(PyObject *self, PyObject *args, PyObject *kwds)
934 {
935 staticmethod *sm = (staticmethod *)self;
936 PyObject *callable;
937
938 if (!_PyArg_NoKeywords("staticmethod", kwds))
939 return -1;
940 if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable))
941 return -1;
942 Py_INCREF(callable);
943 Py_XSETREF(sm->sm_callable, callable);
944 return 0;
945 }
946
947 static PyMemberDef sm_memberlist[] = {
948 {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY},
949 {NULL} /* Sentinel */
950 };
951
952 static PyObject *
sm_get___isabstractmethod__(staticmethod * sm,void * closure)953 sm_get___isabstractmethod__(staticmethod *sm, void *closure)
954 {
955 int res = _PyObject_IsAbstract(sm->sm_callable);
956 if (res == -1) {
957 return NULL;
958 }
959 else if (res) {
960 Py_RETURN_TRUE;
961 }
962 Py_RETURN_FALSE;
963 }
964
965 static PyGetSetDef sm_getsetlist[] = {
966 {"__isabstractmethod__",
967 (getter)sm_get___isabstractmethod__, NULL,
968 NULL,
969 NULL},
970 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
971 {NULL} /* Sentinel */
972 };
973
974 PyDoc_STRVAR(staticmethod_doc,
975 "staticmethod(function) -> method\n\
976 \n\
977 Convert a function to be a static method.\n\
978 \n\
979 A static method does not receive an implicit first argument.\n\
980 To declare a static method, use this idiom:\n\
981 \n\
982 class C:\n\
983 @staticmethod\n\
984 def f(arg1, arg2, ...):\n\
985 ...\n\
986 \n\
987 It can be called either on the class (e.g. C.f()) or on an instance\n\
988 (e.g. C().f()). Both the class and the instance are ignored, and\n\
989 neither is passed implicitly as the first argument to the method.\n\
990 \n\
991 Static methods in Python are similar to those found in Java or C++.\n\
992 For a more advanced concept, see the classmethod builtin.");
993
994 PyTypeObject PyStaticMethod_Type = {
995 PyVarObject_HEAD_INIT(&PyType_Type, 0)
996 "staticmethod",
997 sizeof(staticmethod),
998 0,
999 (destructor)sm_dealloc, /* tp_dealloc */
1000 0, /* tp_vectorcall_offset */
1001 0, /* tp_getattr */
1002 0, /* tp_setattr */
1003 0, /* tp_as_async */
1004 0, /* tp_repr */
1005 0, /* tp_as_number */
1006 0, /* tp_as_sequence */
1007 0, /* tp_as_mapping */
1008 0, /* tp_hash */
1009 0, /* tp_call */
1010 0, /* tp_str */
1011 0, /* tp_getattro */
1012 0, /* tp_setattro */
1013 0, /* tp_as_buffer */
1014 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1015 staticmethod_doc, /* tp_doc */
1016 (traverseproc)sm_traverse, /* tp_traverse */
1017 (inquiry)sm_clear, /* tp_clear */
1018 0, /* tp_richcompare */
1019 0, /* tp_weaklistoffset */
1020 0, /* tp_iter */
1021 0, /* tp_iternext */
1022 0, /* tp_methods */
1023 sm_memberlist, /* tp_members */
1024 sm_getsetlist, /* tp_getset */
1025 0, /* tp_base */
1026 0, /* tp_dict */
1027 sm_descr_get, /* tp_descr_get */
1028 0, /* tp_descr_set */
1029 offsetof(staticmethod, sm_dict), /* tp_dictoffset */
1030 sm_init, /* tp_init */
1031 PyType_GenericAlloc, /* tp_alloc */
1032 PyType_GenericNew, /* tp_new */
1033 PyObject_GC_Del, /* tp_free */
1034 };
1035
1036 PyObject *
PyStaticMethod_New(PyObject * callable)1037 PyStaticMethod_New(PyObject *callable)
1038 {
1039 staticmethod *sm = (staticmethod *)
1040 PyType_GenericAlloc(&PyStaticMethod_Type, 0);
1041 if (sm != NULL) {
1042 Py_INCREF(callable);
1043 sm->sm_callable = callable;
1044 }
1045 return (PyObject *)sm;
1046 }
1047