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