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