funcobject.c 31 KB
Newer Older
1

Guido van Rossum's avatar
Guido van Rossum committed
2 3
/* Function object implementation */

4
#include "Python.h"
5
#include "pycore_object.h"
6 7
#include "pycore_pymem.h"
#include "pycore_pystate.h"
8
#include "pycore_tupleobject.h"
Jeremy Hylton's avatar
Jeremy Hylton committed
9
#include "code.h"
Guido van Rossum's avatar
Guido van Rossum committed
10
#include "structmember.h"
Guido van Rossum's avatar
Guido van Rossum committed
11

12
PyObject *
13
PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
Guido van Rossum's avatar
Guido van Rossum committed
14
{
15 16 17 18
    PyFunctionObject *op;
    PyObject *doc, *consts, *module;
    static PyObject *__name__ = NULL;

19 20 21 22 23 24
    if (__name__ == NULL) {
        __name__ = PyUnicode_InternFromString("__name__");
        if (__name__ == NULL)
            return NULL;
    }

25 26 27 28 29 30 31 32 33 34 35 36 37 38
    op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
    if (op == NULL)
        return NULL;

    op->func_weakreflist = NULL;
    Py_INCREF(code);
    op->func_code = code;
    Py_INCREF(globals);
    op->func_globals = globals;
    op->func_name = ((PyCodeObject *)code)->co_name;
    Py_INCREF(op->func_name);
    op->func_defaults = NULL; /* No default arguments */
    op->func_kwdefaults = NULL; /* No keyword only defaults */
    op->func_closure = NULL;
39

40 41 42 43
    consts = ((PyCodeObject *)code)->co_consts;
    if (PyTuple_Size(consts) >= 1) {
        doc = PyTuple_GetItem(consts, 0);
        if (!PyUnicode_Check(doc))
44
            doc = Py_None;
45 46 47 48 49
    }
    else
        doc = Py_None;
    Py_INCREF(doc);
    op->func_doc = doc;
50

51 52 53
    op->func_dict = NULL;
    op->func_module = NULL;
    op->func_annotations = NULL;
54

55
    /* __module__: If module name is in globals, use it.
56
       Otherwise, use None. */
57
    module = PyDict_GetItemWithError(globals, __name__);
58 59 60 61
    if (module) {
        Py_INCREF(module);
        op->func_module = module;
    }
62 63 64 65
    else if (PyErr_Occurred()) {
        Py_DECREF(op);
        return NULL;
    }
66 67
    if (qualname)
        op->func_qualname = qualname;
68
    else
69 70 71
        op->func_qualname = op->func_name;
    Py_INCREF(op->func_qualname);

72 73
    _PyObject_GC_TRACK(op);
    return (PyObject *)op;
Guido van Rossum's avatar
Guido van Rossum committed
74 75
}

76 77 78 79 80 81
PyObject *
PyFunction_New(PyObject *code, PyObject *globals)
{
    return PyFunction_NewWithQualName(code, globals, NULL);
}

82
PyObject *
83
PyFunction_GetCode(PyObject *op)
Guido van Rossum's avatar
Guido van Rossum committed
84
{
85 86 87 88 89
    if (!PyFunction_Check(op)) {
        PyErr_BadInternalCall();
        return NULL;
    }
    return ((PyFunctionObject *) op) -> func_code;
Guido van Rossum's avatar
Guido van Rossum committed
90 91
}

92
PyObject *
93
PyFunction_GetGlobals(PyObject *op)
Guido van Rossum's avatar
Guido van Rossum committed
94
{
95 96 97 98 99
    if (!PyFunction_Check(op)) {
        PyErr_BadInternalCall();
        return NULL;
    }
    return ((PyFunctionObject *) op) -> func_globals;
Guido van Rossum's avatar
Guido van Rossum committed
100 101
}

102 103 104
PyObject *
PyFunction_GetModule(PyObject *op)
{
105 106 107 108 109
    if (!PyFunction_Check(op)) {
        PyErr_BadInternalCall();
        return NULL;
    }
    return ((PyFunctionObject *) op) -> func_module;
110 111
}

112
PyObject *
113
PyFunction_GetDefaults(PyObject *op)
114
{
115 116 117 118 119
    if (!PyFunction_Check(op)) {
        PyErr_BadInternalCall();
        return NULL;
    }
    return ((PyFunctionObject *) op) -> func_defaults;
120 121 122
}

int
123
PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
124
{
125 126 127 128 129 130 131 132 133 134 135 136 137
    if (!PyFunction_Check(op)) {
        PyErr_BadInternalCall();
        return -1;
    }
    if (defaults == Py_None)
        defaults = NULL;
    else if (defaults && PyTuple_Check(defaults)) {
        Py_INCREF(defaults);
    }
    else {
        PyErr_SetString(PyExc_SystemError, "non-tuple default args");
        return -1;
    }
138
    Py_XSETREF(((PyFunctionObject *)op)->func_defaults, defaults);
139
    return 0;
140 141
}

142 143 144
PyObject *
PyFunction_GetKwDefaults(PyObject *op)
{
145 146 147 148 149
    if (!PyFunction_Check(op)) {
        PyErr_BadInternalCall();
        return NULL;
    }
    return ((PyFunctionObject *) op) -> func_kwdefaults;
150 151 152 153 154
}

int
PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults)
{
155 156 157 158 159 160 161 162 163 164 165 166 167 168
    if (!PyFunction_Check(op)) {
        PyErr_BadInternalCall();
        return -1;
    }
    if (defaults == Py_None)
        defaults = NULL;
    else if (defaults && PyDict_Check(defaults)) {
        Py_INCREF(defaults);
    }
    else {
        PyErr_SetString(PyExc_SystemError,
                        "non-dict keyword only default args");
        return -1;
    }
169
    Py_XSETREF(((PyFunctionObject *)op)->func_kwdefaults, defaults);
170
    return 0;
171 172
}

Jeremy Hylton's avatar
Jeremy Hylton committed
173 174 175
PyObject *
PyFunction_GetClosure(PyObject *op)
{
176 177 178 179 180
    if (!PyFunction_Check(op)) {
        PyErr_BadInternalCall();
        return NULL;
    }
    return ((PyFunctionObject *) op) -> func_closure;
Jeremy Hylton's avatar
Jeremy Hylton committed
181 182 183 184 185
}

int
PyFunction_SetClosure(PyObject *op, PyObject *closure)
{
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    if (!PyFunction_Check(op)) {
        PyErr_BadInternalCall();
        return -1;
    }
    if (closure == Py_None)
        closure = NULL;
    else if (PyTuple_Check(closure)) {
        Py_INCREF(closure);
    }
    else {
        PyErr_Format(PyExc_SystemError,
                     "expected tuple for closure, got '%.100s'",
                     closure->ob_type->tp_name);
        return -1;
    }
201
    Py_XSETREF(((PyFunctionObject *)op)->func_closure, closure);
202
    return 0;
Jeremy Hylton's avatar
Jeremy Hylton committed
203 204
}

205 206 207
PyObject *
PyFunction_GetAnnotations(PyObject *op)
{
208 209 210 211 212
    if (!PyFunction_Check(op)) {
        PyErr_BadInternalCall();
        return NULL;
    }
    return ((PyFunctionObject *) op) -> func_annotations;
213 214 215 216 217
}

int
PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)
{
218 219 220 221 222 223 224 225 226 227 228 229 230 231
    if (!PyFunction_Check(op)) {
        PyErr_BadInternalCall();
        return -1;
    }
    if (annotations == Py_None)
        annotations = NULL;
    else if (annotations && PyDict_Check(annotations)) {
        Py_INCREF(annotations);
    }
    else {
        PyErr_SetString(PyExc_SystemError,
                        "non-dict annotations");
        return -1;
    }
232
    Py_XSETREF(((PyFunctionObject *)op)->func_annotations, annotations);
233
    return 0;
234 235
}

Guido van Rossum's avatar
Guido van Rossum committed
236 237
/* Methods */

238
#define OFF(x) offsetof(PyFunctionObject, x)
Guido van Rossum's avatar
Guido van Rossum committed
239

240
static PyMemberDef func_memberlist[] = {
241 242 243 244 245 246 247
    {"__closure__",   T_OBJECT,     OFF(func_closure),
     RESTRICTED|READONLY},
    {"__doc__",       T_OBJECT,     OFF(func_doc), PY_WRITE_RESTRICTED},
    {"__globals__",   T_OBJECT,     OFF(func_globals),
     RESTRICTED|READONLY},
    {"__module__",    T_OBJECT,     OFF(func_module), PY_WRITE_RESTRICTED},
    {NULL}  /* Sentinel */
Guido van Rossum's avatar
Guido van Rossum committed
248 249
};

250
static PyObject *
251
func_get_code(PyFunctionObject *op, void *Py_UNUSED(ignored))
252
{
253 254 255 256
    if (PySys_Audit("object.__getattr__", "Os", op, "__code__") < 0) {
        return NULL;
    }

257 258
    Py_INCREF(op->func_code);
    return op->func_code;
259 260 261
}

static int
262
func_set_code(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
263
{
264 265 266 267 268 269 270 271 272
    Py_ssize_t nfree, nclosure;

    /* Not legal to del f.func_code or to set it to anything
     * other than a code object. */
    if (value == NULL || !PyCode_Check(value)) {
        PyErr_SetString(PyExc_TypeError,
                        "__code__ must be set to a code object");
        return -1;
    }
273 274 275 276 277 278

    if (PySys_Audit("object.__setattr__", "OsO",
                    op, "__code__", value) < 0) {
        return -1;
    }

279 280 281 282 283 284 285 286 287 288 289 290
    nfree = PyCode_GetNumFree((PyCodeObject *)value);
    nclosure = (op->func_closure == NULL ? 0 :
            PyTuple_GET_SIZE(op->func_closure));
    if (nclosure != nfree) {
        PyErr_Format(PyExc_ValueError,
                     "%U() requires a code object with %zd free vars,"
                     " not %zd",
                     op->func_name,
                     nclosure, nfree);
        return -1;
    }
    Py_INCREF(value);
291
    Py_XSETREF(op->func_code, value);
292
    return 0;
293 294
}

Michael W. Hudson's avatar
Michael W. Hudson committed
295
static PyObject *
296
func_get_name(PyFunctionObject *op, void *Py_UNUSED(ignored))
Michael W. Hudson's avatar
Michael W. Hudson committed
297
{
298 299
    Py_INCREF(op->func_name);
    return op->func_name;
Michael W. Hudson's avatar
Michael W. Hudson committed
300 301 302
}

static int
303
func_set_name(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
Michael W. Hudson's avatar
Michael W. Hudson committed
304
{
305 306 307 308 309 310 311 312
    /* Not legal to del f.func_name or to set it to anything
     * other than a string object. */
    if (value == NULL || !PyUnicode_Check(value)) {
        PyErr_SetString(PyExc_TypeError,
                        "__name__ must be set to a string object");
        return -1;
    }
    Py_INCREF(value);
313
    Py_XSETREF(op->func_name, value);
314
    return 0;
Michael W. Hudson's avatar
Michael W. Hudson committed
315 316
}

317
static PyObject *
318
func_get_qualname(PyFunctionObject *op, void *Py_UNUSED(ignored))
319 320 321 322 323 324
{
    Py_INCREF(op->func_qualname);
    return op->func_qualname;
}

static int
325
func_set_qualname(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
326 327 328 329 330 331 332 333 334
{
    /* Not legal to del f.__qualname__ or to set it to anything
     * other than a string object. */
    if (value == NULL || !PyUnicode_Check(value)) {
        PyErr_SetString(PyExc_TypeError,
                        "__qualname__ must be set to a string object");
        return -1;
    }
    Py_INCREF(value);
335
    Py_XSETREF(op->func_qualname, value);
336 337 338
    return 0;
}

339
static PyObject *
340
func_get_defaults(PyFunctionObject *op, void *Py_UNUSED(ignored))
341
{
342 343 344
    if (PySys_Audit("object.__getattr__", "Os", op, "__defaults__") < 0) {
        return NULL;
    }
345
    if (op->func_defaults == NULL) {
346
        Py_RETURN_NONE;
347 348 349
    }
    Py_INCREF(op->func_defaults);
    return op->func_defaults;
350 351 352
}

static int
353
func_set_defaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
354
{
355 356 357 358 359 360 361 362 363
    /* Legal to del f.func_defaults.
     * Can only set func_defaults to NULL or a tuple. */
    if (value == Py_None)
        value = NULL;
    if (value != NULL && !PyTuple_Check(value)) {
        PyErr_SetString(PyExc_TypeError,
                        "__defaults__ must be set to a tuple object");
        return -1;
    }
364 365 366 367 368 369 370 371 372 373
    if (value) {
        if (PySys_Audit("object.__setattr__", "OsO",
                        op, "__defaults__", value) < 0) {
            return -1;
        }
    } else if (PySys_Audit("object.__delattr__", "Os",
                           op, "__defaults__") < 0) {
        return -1;
    }

374
    Py_XINCREF(value);
375
    Py_XSETREF(op->func_defaults, value);
376
    return 0;
377 378
}

379
static PyObject *
380
func_get_kwdefaults(PyFunctionObject *op, void *Py_UNUSED(ignored))
381
{
382 383 384 385
    if (PySys_Audit("object.__getattr__", "Os",
                    op, "__kwdefaults__") < 0) {
        return NULL;
    }
386
    if (op->func_kwdefaults == NULL) {
387
        Py_RETURN_NONE;
388 389 390
    }
    Py_INCREF(op->func_kwdefaults);
    return op->func_kwdefaults;
391 392 393
}

static int
394
func_set_kwdefaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
395
{
396 397 398 399 400 401 402 403 404
    if (value == Py_None)
        value = NULL;
    /* Legal to del f.func_kwdefaults.
     * Can only set func_kwdefaults to NULL or a dict. */
    if (value != NULL && !PyDict_Check(value)) {
        PyErr_SetString(PyExc_TypeError,
            "__kwdefaults__ must be set to a dict object");
        return -1;
    }
405 406 407 408 409 410 411 412 413 414
    if (value) {
        if (PySys_Audit("object.__setattr__", "OsO",
                        op, "__kwdefaults__", value) < 0) {
            return -1;
        }
    } else if (PySys_Audit("object.__delattr__", "Os",
                           op, "__kwdefaults__") < 0) {
        return -1;
    }

415
    Py_XINCREF(value);
416
    Py_XSETREF(op->func_kwdefaults, value);
417
    return 0;
418 419
}

420
static PyObject *
421
func_get_annotations(PyFunctionObject *op, void *Py_UNUSED(ignored))
422
{
423 424 425 426 427 428 429
    if (op->func_annotations == NULL) {
        op->func_annotations = PyDict_New();
        if (op->func_annotations == NULL)
            return NULL;
    }
    Py_INCREF(op->func_annotations);
    return op->func_annotations;
430 431 432
}

static int
433
func_set_annotations(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
434
{
435 436 437 438 439 440 441 442 443 444 445
    if (value == Py_None)
        value = NULL;
    /* Legal to del f.func_annotations.
     * Can only set func_annotations to NULL (through C api)
     * or a dict. */
    if (value != NULL && !PyDict_Check(value)) {
        PyErr_SetString(PyExc_TypeError,
            "__annotations__ must be set to a dict object");
        return -1;
    }
    Py_XINCREF(value);
446
    Py_XSETREF(op->func_annotations, value);
447
    return 0;
448 449
}

450
static PyGetSetDef func_getsetlist[] = {
451 452 453 454 455 456 457
    {"__code__", (getter)func_get_code, (setter)func_set_code},
    {"__defaults__", (getter)func_get_defaults,
     (setter)func_set_defaults},
    {"__kwdefaults__", (getter)func_get_kwdefaults,
     (setter)func_set_kwdefaults},
    {"__annotations__", (getter)func_get_annotations,
     (setter)func_set_annotations},
458
    {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
459
    {"__name__", (getter)func_get_name, (setter)func_set_name},
460
    {"__qualname__", (getter)func_get_qualname, (setter)func_set_qualname},
461
    {NULL} /* Sentinel */
462 463
};

464 465 466 467
/*[clinic input]
class function "PyFunctionObject *" "&PyFunction_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=70af9c90aa2e71b0]*/
468

469 470 471 472
#include "clinic/funcobject.c.h"

/* function.__new__() maintains the following invariants for closures.
   The closure must correspond to the free variables of the code object.
473 474 475

   if len(code.co_freevars) == 0:
       closure = NULL
476
   else:
477
       len(closure) == len(code.co_freevars)
478 479
   for every elt in closure, type(elt) == cell
*/
480

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
/*[clinic input]
@classmethod
function.__new__ as func_new
    code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
        a code object
    globals: object(subclass_of="&PyDict_Type")
        the globals dictionary
    name: object = None
        a string that overrides the name from the code object
    argdefs as defaults: object = None
        a tuple that specifies the default argument values
    closure: object = None
        a tuple that supplies the bindings for free variables

Create a function object.
[clinic start generated code]*/

498
static PyObject *
499 500 501
func_new_impl(PyTypeObject *type, PyCodeObject *code, PyObject *globals,
              PyObject *name, PyObject *defaults, PyObject *closure)
/*[clinic end generated code: output=99c6d9da3a24e3be input=93611752fc2daf11]*/
502
{
503 504
    PyFunctionObject *newfunc;
    Py_ssize_t nfree, nclosure;
505

506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
    if (name != Py_None && !PyUnicode_Check(name)) {
        PyErr_SetString(PyExc_TypeError,
                        "arg 3 (name) must be None or string");
        return NULL;
    }
    if (defaults != Py_None && !PyTuple_Check(defaults)) {
        PyErr_SetString(PyExc_TypeError,
                        "arg 4 (defaults) must be None or tuple");
        return NULL;
    }
    nfree = PyTuple_GET_SIZE(code->co_freevars);
    if (!PyTuple_Check(closure)) {
        if (nfree && closure == Py_None) {
            PyErr_SetString(PyExc_TypeError,
                            "arg 5 (closure) must be tuple");
            return NULL;
        }
        else if (closure != Py_None) {
            PyErr_SetString(PyExc_TypeError,
                "arg 5 (closure) must be None or tuple");
            return NULL;
        }
    }

    /* check that the closure is well-formed */
    nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
    if (nfree != nclosure)
        return PyErr_Format(PyExc_ValueError,
                            "%U requires closure of length %zd, not %zd",
                            code->co_name, nfree, nclosure);
    if (nclosure) {
        Py_ssize_t i;
        for (i = 0; i < nclosure; i++) {
            PyObject *o = PyTuple_GET_ITEM(closure, i);
            if (!PyCell_Check(o)) {
                return PyErr_Format(PyExc_TypeError,
                    "arg 5 (closure) expected cell, found %s",
                                    o->ob_type->tp_name);
            }
        }
    }
547 548 549
    if (PySys_Audit("function.__new__", "O", code) < 0) {
        return NULL;
    }
550 551 552 553 554 555 556 557

    newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
                                                 globals);
    if (newfunc == NULL)
        return NULL;

    if (name != Py_None) {
        Py_INCREF(name);
558
        Py_SETREF(newfunc->func_name, name);
559 560 561 562 563 564 565 566 567 568 569
    }
    if (defaults != Py_None) {
        Py_INCREF(defaults);
        newfunc->func_defaults  = defaults;
    }
    if (closure != Py_None) {
        Py_INCREF(closure);
        newfunc->func_closure = closure;
    }

    return (PyObject *)newfunc;
570 571
}

572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
static int
func_clear(PyFunctionObject *op)
{
    Py_CLEAR(op->func_code);
    Py_CLEAR(op->func_globals);
    Py_CLEAR(op->func_module);
    Py_CLEAR(op->func_name);
    Py_CLEAR(op->func_defaults);
    Py_CLEAR(op->func_kwdefaults);
    Py_CLEAR(op->func_doc);
    Py_CLEAR(op->func_dict);
    Py_CLEAR(op->func_closure);
    Py_CLEAR(op->func_annotations);
    Py_CLEAR(op->func_qualname);
    return 0;
}

Guido van Rossum's avatar
Guido van Rossum committed
589
static void
590
func_dealloc(PyFunctionObject *op)
Guido van Rossum's avatar
Guido van Rossum committed
591
{
592
    _PyObject_GC_UNTRACK(op);
593
    if (op->func_weakreflist != NULL) {
594
        PyObject_ClearWeakRefs((PyObject *) op);
595 596
    }
    (void)func_clear(op);
597
    PyObject_GC_Del(op);
Guido van Rossum's avatar
Guido van Rossum committed
598 599
}

600
static PyObject*
601
func_repr(PyFunctionObject *op)
602
{
603
    return PyUnicode_FromFormat("<function %U at %p>",
604
                               op->func_qualname, op);
605 606
}

607 608 609
static int
func_traverse(PyFunctionObject *f, visitproc visit, void *arg)
{
610 611 612 613 614 615 616 617 618 619
    Py_VISIT(f->func_code);
    Py_VISIT(f->func_globals);
    Py_VISIT(f->func_module);
    Py_VISIT(f->func_defaults);
    Py_VISIT(f->func_kwdefaults);
    Py_VISIT(f->func_doc);
    Py_VISIT(f->func_name);
    Py_VISIT(f->func_dict);
    Py_VISIT(f->func_closure);
    Py_VISIT(f->func_annotations);
620
    Py_VISIT(f->func_qualname);
621
    return 0;
622 623
}

624
static PyObject *
625
function_call(PyObject *func, PyObject *args, PyObject *kwargs)
626
{
627 628
    PyObject **stack;
    Py_ssize_t nargs;
629

630
    stack = _PyTuple_ITEMS(args);
631 632
    nargs = PyTuple_GET_SIZE(args);
    return _PyFunction_FastCallDict(func, stack, nargs, kwargs);
633 634 635 636 637 638
}

/* Bind a function to an object */
static PyObject *
func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
{
639 640 641 642 643
    if (obj == Py_None || obj == NULL) {
        Py_INCREF(func);
        return func;
    }
    return PyMethod_New(func, obj);
644 645
}

646
PyTypeObject PyFunction_Type = {
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "function",
    sizeof(PyFunctionObject),
    0,
    (destructor)func_dealloc,                   /* tp_dealloc */
    0,                                          /* tp_print */
    0,                                          /* tp_getattr */
    0,                                          /* tp_setattr */
    0,                                          /* tp_reserved */
    (reprfunc)func_repr,                        /* tp_repr */
    0,                                          /* tp_as_number */
    0,                                          /* tp_as_sequence */
    0,                                          /* tp_as_mapping */
    0,                                          /* tp_hash */
    function_call,                              /* tp_call */
    0,                                          /* tp_str */
Benjamin Peterson's avatar
Benjamin Peterson committed
663 664
    0,                                          /* tp_getattro */
    0,                                          /* tp_setattro */
665
    0,                                          /* tp_as_buffer */
666 667
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
    func_new__doc__,                            /* tp_doc */
668
    (traverseproc)func_traverse,                /* tp_traverse */
669
    (inquiry)func_clear,                        /* tp_clear */
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
    0,                                          /* tp_richcompare */
    offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
    0,                                          /* tp_iter */
    0,                                          /* tp_iternext */
    0,                                          /* tp_methods */
    func_memberlist,                            /* tp_members */
    func_getsetlist,                            /* tp_getset */
    0,                                          /* tp_base */
    0,                                          /* tp_dict */
    func_descr_get,                             /* tp_descr_get */
    0,                                          /* tp_descr_set */
    offsetof(PyFunctionObject, func_dict),      /* tp_dictoffset */
    0,                                          /* tp_init */
    0,                                          /* tp_alloc */
    func_new,                                   /* tp_new */
685 686 687 688 689 690 691 692 693 694
};


/* Class method object */

/* A class method receives the class as implicit first argument,
   just like an instance method receives the instance.
   To declare a class method, use this idiom:

     class C:
695 696 697
         @classmethod
         def f(cls, arg1, arg2, ...):
             ...
698

699 700 701 702 703 704 705 706 707 708
   It can be called either on the class (e.g. C.f()) or on an instance
   (e.g. C().f()); the instance is ignored except for its class.
   If a class method is called for a derived class, the derived class
   object is passed as the implied first argument.

   Class methods are different than C++ or Java static methods.
   If you want those, see static methods below.
*/

typedef struct {
709 710
    PyObject_HEAD
    PyObject *cm_callable;
711
    PyObject *cm_dict;
712 713 714 715 716
} classmethod;

static void
cm_dealloc(classmethod *cm)
{
717 718
    _PyObject_GC_UNTRACK((PyObject *)cm);
    Py_XDECREF(cm->cm_callable);
719
    Py_XDECREF(cm->cm_dict);
720
    Py_TYPE(cm)->tp_free((PyObject *)cm);
721 722
}

723 724 725
static int
cm_traverse(classmethod *cm, visitproc visit, void *arg)
{
726
    Py_VISIT(cm->cm_callable);
727
    Py_VISIT(cm->cm_dict);
728
    return 0;
729 730 731 732 733
}

static int
cm_clear(classmethod *cm)
{
734
    Py_CLEAR(cm->cm_callable);
735
    Py_CLEAR(cm->cm_dict);
736
    return 0;
737 738 739
}


740 741 742
static PyObject *
cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
{
743
    classmethod *cm = (classmethod *)self;
744

745 746 747 748 749 750 751 752
    if (cm->cm_callable == NULL) {
        PyErr_SetString(PyExc_RuntimeError,
                        "uninitialized classmethod object");
        return NULL;
    }
    if (type == NULL)
        type = (PyObject *)(Py_TYPE(obj));
    return PyMethod_New(cm->cm_callable, type);
753 754 755 756 757
}

static int
cm_init(PyObject *self, PyObject *args, PyObject *kwds)
{
758 759
    classmethod *cm = (classmethod *)self;
    PyObject *callable;
760

761 762
    if (!_PyArg_NoKeywords("classmethod", kwds))
        return -1;
763 764
    if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable))
        return -1;
765
    Py_INCREF(callable);
766
    Py_XSETREF(cm->cm_callable, callable);
767
    return 0;
768 769
}

770
static PyMemberDef cm_memberlist[] = {
771 772
    {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY},
    {NULL}  /* Sentinel */
773 774
};

775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
static PyObject *
cm_get___isabstractmethod__(classmethod *cm, void *closure)
{
    int res = _PyObject_IsAbstract(cm->cm_callable);
    if (res == -1) {
        return NULL;
    }
    else if (res) {
        Py_RETURN_TRUE;
    }
    Py_RETURN_FALSE;
}

static PyGetSetDef cm_getsetlist[] = {
    {"__isabstractmethod__",
     (getter)cm_get___isabstractmethod__, NULL,
     NULL,
     NULL},
793
    {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
794 795 796
    {NULL} /* Sentinel */
};

797
PyDoc_STRVAR(classmethod_doc,
798 799 800 801 802 803 804 805 806
"classmethod(function) -> method\n\
\n\
Convert a function to be a class method.\n\
\n\
A class method receives the class as implicit first argument,\n\
just like an instance method receives the instance.\n\
To declare a class method, use this idiom:\n\
\n\
  class C:\n\
807 808 809
      @classmethod\n\
      def f(cls, arg1, arg2, ...):\n\
          ...\n\
810 811 812 813 814
\n\
It can be called either on the class (e.g. C.f()) or on an instance\n\
(e.g. C().f()).  The instance is ignored except for its class.\n\
If a class method is called for a derived class, the derived class\n\
object is passed as the implied first argument.\n\
815
\n\
816
Class methods are different than C++ or Java static methods.\n\
817
If you want those, see the staticmethod builtin.");
818

819
PyTypeObject PyClassMethod_Type = {
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "classmethod",
    sizeof(classmethod),
    0,
    (destructor)cm_dealloc,                     /* tp_dealloc */
    0,                                          /* tp_print */
    0,                                          /* tp_getattr */
    0,                                          /* tp_setattr */
    0,                                          /* tp_reserved */
    0,                                          /* tp_repr */
    0,                                          /* tp_as_number */
    0,                                          /* tp_as_sequence */
    0,                                          /* tp_as_mapping */
    0,                                          /* tp_hash */
    0,                                          /* tp_call */
    0,                                          /* tp_str */
Benjamin Peterson's avatar
Benjamin Peterson committed
836
    0,                                          /* tp_getattro */
837 838 839 840 841 842 843 844 845 846 847 848
    0,                                          /* tp_setattro */
    0,                                          /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
    classmethod_doc,                            /* tp_doc */
    (traverseproc)cm_traverse,                  /* tp_traverse */
    (inquiry)cm_clear,                          /* tp_clear */
    0,                                          /* tp_richcompare */
    0,                                          /* tp_weaklistoffset */
    0,                                          /* tp_iter */
    0,                                          /* tp_iternext */
    0,                                          /* tp_methods */
    cm_memberlist,              /* tp_members */
849
    cm_getsetlist,                              /* tp_getset */
850 851 852 853
    0,                                          /* tp_base */
    0,                                          /* tp_dict */
    cm_descr_get,                               /* tp_descr_get */
    0,                                          /* tp_descr_set */
854
    offsetof(classmethod, cm_dict),             /* tp_dictoffset */
855 856 857 858
    cm_init,                                    /* tp_init */
    PyType_GenericAlloc,                        /* tp_alloc */
    PyType_GenericNew,                          /* tp_new */
    PyObject_GC_Del,                            /* tp_free */
859 860 861 862 863
};

PyObject *
PyClassMethod_New(PyObject *callable)
{
864 865 866 867 868 869 870
    classmethod *cm = (classmethod *)
        PyType_GenericAlloc(&PyClassMethod_Type, 0);
    if (cm != NULL) {
        Py_INCREF(callable);
        cm->cm_callable = callable;
    }
    return (PyObject *)cm;
871 872 873 874 875 876 877 878 879
}


/* Static method object */

/* A static method does not receive an implicit first argument.
   To declare a static method, use this idiom:

     class C:
880 881 882
         @staticmethod
         def f(arg1, arg2, ...):
             ...
883 884

   It can be called either on the class (e.g. C.f()) or on an instance
885 886
   (e.g. C().f()). Both the class and the instance are ignored, and
   neither is passed implicitly as the first argument to the method.
887 888 889 890 891 892

   Static methods in Python are similar to those found in Java or C++.
   For a more advanced concept, see class methods above.
*/

typedef struct {
893 894
    PyObject_HEAD
    PyObject *sm_callable;
895
    PyObject *sm_dict;
896 897 898 899 900
} staticmethod;

static void
sm_dealloc(staticmethod *sm)
{
901 902
    _PyObject_GC_UNTRACK((PyObject *)sm);
    Py_XDECREF(sm->sm_callable);
903
    Py_XDECREF(sm->sm_dict);
904
    Py_TYPE(sm)->tp_free((PyObject *)sm);
905 906
}

907 908 909
static int
sm_traverse(staticmethod *sm, visitproc visit, void *arg)
{
910
    Py_VISIT(sm->sm_callable);
911
    Py_VISIT(sm->sm_dict);
912
    return 0;
913 914 915 916 917
}

static int
sm_clear(staticmethod *sm)
{
Benjamin Peterson's avatar
Benjamin Peterson committed
918
    Py_CLEAR(sm->sm_callable);
919
    Py_CLEAR(sm->sm_dict);
920
    return 0;
921 922
}

923 924 925
static PyObject *
sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
{
926
    staticmethod *sm = (staticmethod *)self;
927

928 929 930 931 932 933 934
    if (sm->sm_callable == NULL) {
        PyErr_SetString(PyExc_RuntimeError,
                        "uninitialized staticmethod object");
        return NULL;
    }
    Py_INCREF(sm->sm_callable);
    return sm->sm_callable;
935 936 937 938 939
}

static int
sm_init(PyObject *self, PyObject *args, PyObject *kwds)
{
940 941
    staticmethod *sm = (staticmethod *)self;
    PyObject *callable;
942

943 944
    if (!_PyArg_NoKeywords("staticmethod", kwds))
        return -1;
945 946
    if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable))
        return -1;
947
    Py_INCREF(callable);
948
    Py_XSETREF(sm->sm_callable, callable);
949
    return 0;
950 951
}

952
static PyMemberDef sm_memberlist[] = {
953 954
    {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY},
    {NULL}  /* Sentinel */
955 956
};

957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
static PyObject *
sm_get___isabstractmethod__(staticmethod *sm, void *closure)
{
    int res = _PyObject_IsAbstract(sm->sm_callable);
    if (res == -1) {
        return NULL;
    }
    else if (res) {
        Py_RETURN_TRUE;
    }
    Py_RETURN_FALSE;
}

static PyGetSetDef sm_getsetlist[] = {
    {"__isabstractmethod__",
     (getter)sm_get___isabstractmethod__, NULL,
     NULL,
     NULL},
975
    {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
976 977 978
    {NULL} /* Sentinel */
};

979
PyDoc_STRVAR(staticmethod_doc,
980 981 982 983 984 985 986 987
"staticmethod(function) -> method\n\
\n\
Convert a function to be a static method.\n\
\n\
A static method does not receive an implicit first argument.\n\
To declare a static method, use this idiom:\n\
\n\
     class C:\n\
988 989 990
         @staticmethod\n\
         def f(arg1, arg2, ...):\n\
             ...\n\
991 992
\n\
It can be called either on the class (e.g. C.f()) or on an instance\n\
993 994
(e.g. C().f()). Both the class and the instance are ignored, and\n\
neither is passed implicitly as the first argument to the method.\n\
995 996
\n\
Static methods in Python are similar to those found in Java or C++.\n\
997
For a more advanced concept, see the classmethod builtin.");
998

999
PyTypeObject PyStaticMethod_Type = {
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "staticmethod",
    sizeof(staticmethod),
    0,
    (destructor)sm_dealloc,                     /* tp_dealloc */
    0,                                          /* tp_print */
    0,                                          /* tp_getattr */
    0,                                          /* tp_setattr */
    0,                                          /* tp_reserved */
    0,                                          /* tp_repr */
    0,                                          /* tp_as_number */
    0,                                          /* tp_as_sequence */
    0,                                          /* tp_as_mapping */
    0,                                          /* tp_hash */
    0,                                          /* tp_call */
    0,                                          /* tp_str */
1016
    0,                                          /* tp_getattro */
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
    0,                                          /* tp_setattro */
    0,                                          /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
    staticmethod_doc,                           /* tp_doc */
    (traverseproc)sm_traverse,                  /* tp_traverse */
    (inquiry)sm_clear,                          /* tp_clear */
    0,                                          /* tp_richcompare */
    0,                                          /* tp_weaklistoffset */
    0,                                          /* tp_iter */
    0,                                          /* tp_iternext */
    0,                                          /* tp_methods */
    sm_memberlist,              /* tp_members */
1029
    sm_getsetlist,                              /* tp_getset */
1030 1031 1032 1033
    0,                                          /* tp_base */
    0,                                          /* tp_dict */
    sm_descr_get,                               /* tp_descr_get */
    0,                                          /* tp_descr_set */
1034
    offsetof(staticmethod, sm_dict),            /* tp_dictoffset */
1035 1036 1037 1038
    sm_init,                                    /* tp_init */
    PyType_GenericAlloc,                        /* tp_alloc */
    PyType_GenericNew,                          /* tp_new */
    PyObject_GC_Del,                            /* tp_free */
Guido van Rossum's avatar
Guido van Rossum committed
1039
};
1040 1041 1042 1043

PyObject *
PyStaticMethod_New(PyObject *callable)
{
1044 1045 1046 1047 1048 1049 1050
    staticmethod *sm = (staticmethod *)
        PyType_GenericAlloc(&PyStaticMethod_Type, 0);
    if (sm != NULL) {
        Py_INCREF(callable);
        sm->sm_callable = callable;
    }
    return (PyObject *)sm;
1051
}