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