Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/classobject.c
Line
Count
Source
1
/* Class object implementation (dead now except for methods) */
2
3
#include "Python.h"
4
#include "pycore_call.h"          // _PyObject_VectorcallTstate()
5
#include "pycore_ceval.h"         // _PyEval_GetBuiltin()
6
#include "pycore_freelist.h"
7
#include "pycore_object.h"
8
#include "pycore_pyerrors.h"
9
#include "pycore_pystate.h"       // _PyThreadState_GET()
10
#include "pycore_symtable.h"      // _Py_Mangle()
11
#include "pycore_weakref.h"       // FT_CLEAR_WEAKREFS()
12
13
14
#include "clinic/classobject.c.h"
15
16
50.0M
#define _PyMethodObject_CAST(op) _Py_CAST(PyMethodObject*, (op))
17
20
#define TP_DESCR_GET(t) ((t)->tp_descr_get)
18
19
/*[clinic input]
20
class method "PyMethodObject *" "&PyMethod_Type"
21
[clinic start generated code]*/
22
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b16e47edf6107c23]*/
23
24
25
PyObject *
26
PyMethod_Function(PyObject *im)
27
0
{
28
0
    if (!PyMethod_Check(im)) {
29
0
        PyErr_BadInternalCall();
30
0
        return NULL;
31
0
    }
32
0
    return ((PyMethodObject *)im)->im_func;
33
0
}
34
35
PyObject *
36
PyMethod_Self(PyObject *im)
37
0
{
38
0
    if (!PyMethod_Check(im)) {
39
0
        PyErr_BadInternalCall();
40
0
        return NULL;
41
0
    }
42
0
    return ((PyMethodObject *)im)->im_self;
43
0
}
44
45
46
static PyObject *
47
method_vectorcall(PyObject *method, PyObject *const *args,
48
                  size_t nargsf, PyObject *kwnames)
49
44.5M
{
50
44.5M
    assert(Py_IS_TYPE(method, &PyMethod_Type));
51
52
44.5M
    PyThreadState *tstate = _PyThreadState_GET();
53
44.5M
    PyObject *self = PyMethod_GET_SELF(method);
54
44.5M
    PyObject *func = PyMethod_GET_FUNCTION(method);
55
44.5M
    return _PyObject_VectorcallPrepend(tstate, func, self, args, nargsf, kwnames);
56
44.5M
}
57
58
59
/* Method objects are used for bound instance methods returned by
60
   instancename.methodname. ClassName.methodname returns an ordinary
61
   function.
62
*/
63
64
PyObject *
65
PyMethod_New(PyObject *func, PyObject *self)
66
48.1M
{
67
48.1M
    if (self == NULL) {
68
0
        PyErr_BadInternalCall();
69
0
        return NULL;
70
0
    }
71
48.1M
    PyMethodObject *im = _Py_FREELIST_POP(PyMethodObject, pymethodobjects);
72
48.1M
    if (im == NULL) {
73
796k
        im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
74
796k
        if (im == NULL) {
75
0
            return NULL;
76
0
        }
77
796k
    }
78
48.1M
    im->im_weakreflist = NULL;
79
48.1M
    im->im_func = Py_NewRef(func);
80
48.1M
    im->im_self = Py_NewRef(self);
81
48.1M
    im->vectorcall = method_vectorcall;
82
48.1M
    _PyObject_GC_TRACK(im);
83
48.1M
    return (PyObject *)im;
84
48.1M
}
85
86
/*[clinic input]
87
method.__reduce__
88
[clinic start generated code]*/
89
90
static PyObject *
91
method___reduce___impl(PyMethodObject *self)
92
/*[clinic end generated code: output=6c04506d0fa6fdcb input=143a0bf5e96de6e8]*/
93
0
{
94
0
    PyObject *funcself = PyMethod_GET_SELF(self);
95
0
    PyObject *func = PyMethod_GET_FUNCTION(self);
96
0
    PyObject *funcname = PyObject_GetAttr(func, &_Py_ID(__name__));
97
0
    if (funcname == NULL) {
98
0
        return NULL;
99
0
    }
100
0
    if (_Py_IsPrivateName(funcname)) {
101
0
        PyObject *classname = PyType_Check(funcself)
102
0
            ? PyType_GetName((PyTypeObject *)funcself)
103
0
            : PyType_GetName(Py_TYPE(funcself));
104
0
        if (classname == NULL) {
105
0
            Py_DECREF(funcname);
106
0
            return NULL;
107
0
        }
108
0
        Py_SETREF(funcname, _Py_Mangle(classname, funcname));
109
0
        Py_DECREF(classname);
110
0
        if (funcname == NULL) {
111
0
            return NULL;
112
0
        }
113
0
    }
114
0
    return Py_BuildValue(
115
0
            "N(ON)", _PyEval_GetBuiltin(&_Py_ID(getattr)), funcself, funcname);
116
0
}
117
118
static PyMethodDef method_methods[] = {
119
    METHOD___REDUCE___METHODDEF
120
    {NULL, NULL}
121
};
122
123
/* Descriptors for PyMethod attributes */
124
125
/* im_func and im_self are stored in the PyMethod object */
126
127
#define MO_OFF(x) offsetof(PyMethodObject, x)
128
129
static PyMemberDef method_memberlist[] = {
130
    {"__func__", _Py_T_OBJECT, MO_OFF(im_func), Py_READONLY,
131
     "the function (or other callable) implementing a method"},
132
    {"__self__", _Py_T_OBJECT, MO_OFF(im_self), Py_READONLY,
133
     "the instance to which a method is bound"},
134
    {NULL}      /* Sentinel */
135
};
136
137
/* Christian Tismer argued convincingly that method attributes should
138
   (nearly) always override function attributes.
139
   The one exception is __doc__; there's a default __doc__ which
140
   should only be used for the class, not for instances */
141
142
static PyObject *
143
method_get_doc(PyObject *self, void *context)
144
20
{
145
20
    PyMethodObject *im = _PyMethodObject_CAST(self);
146
20
    return PyObject_GetAttr(im->im_func, &_Py_ID(__doc__));
147
20
}
148
149
static PyGetSetDef method_getset[] = {
150
    {"__doc__", method_get_doc, NULL, NULL},
151
    {0}
152
};
153
154
static PyObject *
155
method_getattro(PyObject *obj, PyObject *name)
156
148
{
157
148
    PyMethodObject *im = (PyMethodObject *)obj;
158
148
    PyTypeObject *tp = Py_TYPE(obj);
159
148
    PyObject *descr = NULL;
160
161
148
    {
162
148
        if (!_PyType_IsReady(tp)) {
163
0
            if (PyType_Ready(tp) < 0)
164
0
                return NULL;
165
0
        }
166
148
        descr = _PyType_LookupRef(tp, name);
167
148
    }
168
169
148
    if (descr != NULL) {
170
20
        descrgetfunc f = TP_DESCR_GET(Py_TYPE(descr));
171
20
        if (f != NULL) {
172
20
            PyObject *res = f(descr, obj, (PyObject *)Py_TYPE(obj));
173
20
            Py_DECREF(descr);
174
20
            return res;
175
20
        }
176
0
        else {
177
0
            return descr;
178
0
        }
179
20
    }
180
181
128
    return PyObject_GetAttr(im->im_func, name);
182
148
}
183
184
/*[clinic input]
185
@vectorcall
186
@classmethod
187
method.__new__ as method_type_new
188
    function: object
189
    instance: object
190
    /
191
192
Create a bound instance method object.
193
[clinic start generated code]*/
194
195
static PyObject *
196
method_type_new_impl(PyTypeObject *type, PyObject *function,
197
                     PyObject *instance)
198
/*[clinic end generated code: output=e9877864a8bfdf70 input=70c1e0da5d6267f5]*/
199
20
{
200
20
    if (!PyCallable_Check(function)) {
201
0
        PyErr_SetString(PyExc_TypeError,
202
0
                        "first argument must be callable");
203
0
        return NULL;
204
0
    }
205
20
    if (instance == NULL || instance == Py_None) {
206
0
        PyErr_SetString(PyExc_TypeError,
207
0
            "instance must not be None");
208
0
        return NULL;
209
0
    }
210
211
20
    return PyMethod_New(function, instance);
212
20
}
213
214
static void
215
method_dealloc(PyObject *self)
216
48.1M
{
217
48.1M
    PyMethodObject *im = _PyMethodObject_CAST(self);
218
48.1M
    _PyObject_GC_UNTRACK(im);
219
48.1M
    FT_CLEAR_WEAKREFS(self, im->im_weakreflist);
220
48.1M
    Py_DECREF(im->im_func);
221
48.1M
    Py_XDECREF(im->im_self);
222
48.1M
    assert(Py_IS_TYPE(self, &PyMethod_Type));
223
48.1M
    _Py_FREELIST_FREE(pymethodobjects, (PyObject *)im, PyObject_GC_Del);
224
48.1M
}
225
226
static PyObject *
227
method_richcompare(PyObject *self, PyObject *other, int op)
228
0
{
229
0
    PyMethodObject *a, *b;
230
0
    PyObject *res;
231
0
    int eq;
232
233
0
    if ((op != Py_EQ && op != Py_NE) ||
234
0
        !PyMethod_Check(self) ||
235
0
        !PyMethod_Check(other))
236
0
    {
237
0
        Py_RETURN_NOTIMPLEMENTED;
238
0
    }
239
0
    a = (PyMethodObject *)self;
240
0
    b = (PyMethodObject *)other;
241
0
    eq = PyObject_RichCompareBool(a->im_func, b->im_func, Py_EQ);
242
0
    if (eq == 1) {
243
0
        eq = (a->im_self == b->im_self);
244
0
    }
245
0
    else if (eq < 0)
246
0
        return NULL;
247
0
    if (op == Py_EQ)
248
0
        res = eq ? Py_True : Py_False;
249
0
    else
250
0
        res = eq ? Py_False : Py_True;
251
0
    return Py_NewRef(res);
252
0
}
253
254
static PyObject *
255
method_repr(PyObject *op)
256
0
{
257
0
    PyMethodObject *a = _PyMethodObject_CAST(op);
258
0
    PyObject *self = a->im_self;
259
0
    PyObject *func = a->im_func;
260
0
    PyObject *funcname, *result;
261
0
    const char *defname = "?";
262
263
0
    if (PyObject_GetOptionalAttr(func, &_Py_ID(__qualname__), &funcname) < 0 ||
264
0
        (funcname == NULL &&
265
0
         PyObject_GetOptionalAttr(func, &_Py_ID(__name__), &funcname) < 0))
266
0
    {
267
0
        return NULL;
268
0
    }
269
270
0
    if (funcname != NULL && !PyUnicode_Check(funcname)) {
271
0
        Py_SETREF(funcname, NULL);
272
0
    }
273
274
    /* XXX Shouldn't use repr()/%R here! */
275
0
    result = PyUnicode_FromFormat("<bound method %V of %R>",
276
0
                                  funcname, defname, self);
277
278
0
    Py_XDECREF(funcname);
279
0
    return result;
280
0
}
281
282
static Py_hash_t
283
method_hash(PyObject *self)
284
0
{
285
0
    PyMethodObject *a = _PyMethodObject_CAST(self);
286
0
    Py_hash_t x = PyObject_GenericHash(a->im_self);
287
0
    Py_hash_t y = PyObject_Hash(a->im_func);
288
0
    if (y == -1) {
289
0
        return -1;
290
0
    }
291
292
0
    x = x ^ y;
293
0
    if (x == -1) {
294
0
        x = -2;
295
0
    }
296
0
    return x;
297
0
}
298
299
static int
300
method_traverse(PyObject *self, visitproc visit, void *arg)
301
1.82M
{
302
1.82M
    PyMethodObject *im = _PyMethodObject_CAST(self);
303
1.82M
    Py_VISIT(im->im_func);
304
1.82M
    Py_VISIT(im->im_self);
305
1.82M
    return 0;
306
1.82M
}
307
308
static PyObject *
309
method_descr_get(PyObject *meth, PyObject *obj, PyObject *cls)
310
26
{
311
26
    Py_INCREF(meth);
312
26
    return meth;
313
26
}
314
315
PyTypeObject PyMethod_Type = {
316
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
317
    .tp_name = "method",
318
    .tp_basicsize = sizeof(PyMethodObject),
319
    .tp_dealloc = method_dealloc,
320
    .tp_vectorcall_offset = offsetof(PyMethodObject, vectorcall),
321
    .tp_repr = method_repr,
322
    .tp_hash = method_hash,
323
    .tp_call = PyVectorcall_Call,
324
    .tp_getattro = method_getattro,
325
    .tp_setattro = PyObject_GenericSetAttr,
326
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
327
                Py_TPFLAGS_HAVE_VECTORCALL,
328
    .tp_doc = method_type_new__doc__,
329
    .tp_traverse = method_traverse,
330
    .tp_richcompare = method_richcompare,
331
    .tp_weaklistoffset = offsetof(PyMethodObject, im_weakreflist),
332
    .tp_methods = method_methods,
333
    .tp_members = method_memberlist,
334
    .tp_getset = method_getset,
335
    .tp_descr_get = method_descr_get,
336
    .tp_new = method_type_new,
337
    .tp_vectorcall = method_type_vectorcall,
338
};
339
340
/* ------------------------------------------------------------------------
341
 * instance method
342
 */
343
344
/*[clinic input]
345
class instancemethod "PyInstanceMethodObject *" "&PyInstanceMethod_Type"
346
[clinic start generated code]*/
347
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=28c9762a9016f4d2]*/
348
349
PyObject *
350
0
PyInstanceMethod_New(PyObject *func) {
351
0
    PyInstanceMethodObject *method;
352
0
    method = PyObject_GC_New(PyInstanceMethodObject,
353
0
                             &PyInstanceMethod_Type);
354
0
    if (method == NULL) return NULL;
355
0
    method->func = Py_NewRef(func);
356
0
    _PyObject_GC_TRACK(method);
357
0
    return (PyObject *)method;
358
0
}
359
360
PyObject *
361
PyInstanceMethod_Function(PyObject *im)
362
0
{
363
0
    if (!PyInstanceMethod_Check(im)) {
364
0
        PyErr_BadInternalCall();
365
0
        return NULL;
366
0
    }
367
0
    return PyInstanceMethod_GET_FUNCTION(im);
368
0
}
369
370
#define IMO_OFF(x) offsetof(PyInstanceMethodObject, x)
371
372
static PyMemberDef instancemethod_memberlist[] = {
373
    {"__func__", _Py_T_OBJECT, IMO_OFF(func), Py_READONLY,
374
     "the function (or other callable) implementing a method"},
375
    {NULL}      /* Sentinel */
376
};
377
378
static PyObject *
379
instancemethod_get_doc(PyObject *self, void *context)
380
0
{
381
0
    return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self),
382
0
                            &_Py_ID(__doc__));
383
0
}
384
385
static PyGetSetDef instancemethod_getset[] = {
386
    {"__doc__", instancemethod_get_doc, NULL, NULL},
387
    {0}
388
};
389
390
static PyObject *
391
instancemethod_getattro(PyObject *self, PyObject *name)
392
0
{
393
0
    PyTypeObject *tp = Py_TYPE(self);
394
0
    PyObject *descr = NULL;
395
396
0
    if (!_PyType_IsReady(tp)) {
397
0
        if (PyType_Ready(tp) < 0)
398
0
            return NULL;
399
0
    }
400
0
    descr = _PyType_LookupRef(tp, name);
401
402
0
    if (descr != NULL) {
403
0
        descrgetfunc f = TP_DESCR_GET(Py_TYPE(descr));
404
0
        if (f != NULL) {
405
0
            PyObject *res = f(descr, self, (PyObject *)Py_TYPE(self));
406
0
            Py_DECREF(descr);
407
0
            return res;
408
0
        }
409
0
        else {
410
0
            return descr;
411
0
        }
412
0
    }
413
414
0
    return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), name);
415
0
}
416
417
static void
418
0
instancemethod_dealloc(PyObject *self) {
419
0
    _PyObject_GC_UNTRACK(self);
420
0
    Py_DECREF(PyInstanceMethod_GET_FUNCTION(self));
421
0
    PyObject_GC_Del(self);
422
0
}
423
424
static int
425
0
instancemethod_traverse(PyObject *self, visitproc visit, void *arg) {
426
0
    Py_VISIT(PyInstanceMethod_GET_FUNCTION(self));
427
0
    return 0;
428
0
}
429
430
static PyObject *
431
instancemethod_call(PyObject *self, PyObject *arg, PyObject *kw)
432
0
{
433
0
    return PyObject_Call(PyInstanceMethod_GET_FUNCTION(self), arg, kw);
434
0
}
435
436
static PyObject *
437
0
instancemethod_descr_get(PyObject *descr, PyObject *obj, PyObject *type) {
438
0
    PyObject *func = PyInstanceMethod_GET_FUNCTION(descr);
439
0
    if (obj == NULL) {
440
0
        return Py_NewRef(func);
441
0
    }
442
0
    else
443
0
        return PyMethod_New(func, obj);
444
0
}
445
446
static PyObject *
447
instancemethod_richcompare(PyObject *self, PyObject *other, int op)
448
0
{
449
0
    PyInstanceMethodObject *a, *b;
450
0
    PyObject *res;
451
0
    int eq;
452
453
0
    if ((op != Py_EQ && op != Py_NE) ||
454
0
        !PyInstanceMethod_Check(self) ||
455
0
        !PyInstanceMethod_Check(other))
456
0
    {
457
0
        Py_RETURN_NOTIMPLEMENTED;
458
0
    }
459
0
    a = (PyInstanceMethodObject *)self;
460
0
    b = (PyInstanceMethodObject *)other;
461
0
    eq = PyObject_RichCompareBool(a->func, b->func, Py_EQ);
462
0
    if (eq < 0)
463
0
        return NULL;
464
0
    if (op == Py_EQ)
465
0
        res = eq ? Py_True : Py_False;
466
0
    else
467
0
        res = eq ? Py_False : Py_True;
468
0
    return Py_NewRef(res);
469
0
}
470
471
static PyObject *
472
instancemethod_repr(PyObject *self)
473
0
{
474
0
    PyObject *func = PyInstanceMethod_Function(self);
475
0
    PyObject *funcname, *result;
476
0
    const char *defname = "?";
477
478
0
    if (func == NULL) {
479
0
        PyErr_BadInternalCall();
480
0
        return NULL;
481
0
    }
482
483
0
    if (PyObject_GetOptionalAttr(func, &_Py_ID(__name__), &funcname) < 0) {
484
0
        return NULL;
485
0
    }
486
0
    if (funcname != NULL && !PyUnicode_Check(funcname)) {
487
0
        Py_SETREF(funcname, NULL);
488
0
    }
489
490
0
    result = PyUnicode_FromFormat("<instancemethod %V at %p>",
491
0
                                  funcname, defname, self);
492
493
0
    Py_XDECREF(funcname);
494
0
    return result;
495
0
}
496
497
/*[clinic input]
498
@classmethod
499
instancemethod.__new__ as instancemethod_new
500
    function: object
501
    /
502
503
Bind a function to a class.
504
[clinic start generated code]*/
505
506
static PyObject *
507
instancemethod_new_impl(PyTypeObject *type, PyObject *function)
508
/*[clinic end generated code: output=5e0397b2bdb750be input=cfc54e8b973664a8]*/
509
0
{
510
0
    if (!PyCallable_Check(function)) {
511
0
        PyErr_SetString(PyExc_TypeError,
512
0
                        "first argument must be callable");
513
0
        return NULL;
514
0
    }
515
516
0
    return PyInstanceMethod_New(function);
517
0
}
518
519
PyTypeObject PyInstanceMethod_Type = {
520
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
521
    .tp_name = "instancemethod",
522
    .tp_basicsize = sizeof(PyInstanceMethodObject),
523
    .tp_dealloc = instancemethod_dealloc,
524
    .tp_repr = instancemethod_repr,
525
    .tp_call = instancemethod_call,
526
    .tp_getattro = instancemethod_getattro,
527
    .tp_setattro = PyObject_GenericSetAttr,
528
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
529
    .tp_doc = instancemethod_new__doc__,
530
    .tp_traverse = instancemethod_traverse,
531
    .tp_richcompare = instancemethod_richcompare,
532
    .tp_members = instancemethod_memberlist,
533
    .tp_getset = instancemethod_getset,
534
    .tp_descr_get = instancemethod_descr_get,
535
    .tp_new = instancemethod_new,
536
};