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