Python-2.7.3/Objects/funcobject.c

No issues found

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