Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/funcobject.c
Line
Count
Source
1
/* Function object implementation */
2
3
#include "Python.h"
4
#include "pycore_code.h"          // _PyCode_VerifyStateless()
5
#include "pycore_dict.h"          // _Py_INCREF_DICT()
6
#include "pycore_function.h"      // _PyFunction_Vectorcall
7
#include "pycore_long.h"          // _PyLong_GetOne()
8
#include "pycore_modsupport.h"    // _PyArg_NoKeywords()
9
#include "pycore_object.h"        // _PyObject_GC_UNTRACK()
10
#include "pycore_object_deferred.h" // _PyObject_SetDeferredRefcount()
11
#include "pycore_optimizer.h"       // _Py_Executors_InvalidateDependency()
12
#include "pycore_pyerrors.h"      // _PyErr_Occurred()
13
#include "pycore_setobject.h"     // _PySet_NextEntry()
14
#include "pycore_stats.h"
15
#include "pycore_weakref.h"       // FT_CLEAR_WEAKREFS()
16
17
static const char *
18
0
func_event_name(PyFunction_WatchEvent event) {
19
0
    switch (event) {
20
0
        #define CASE(op)                \
21
0
        case PyFunction_EVENT_##op:         \
22
0
            return "PyFunction_EVENT_" #op;
23
0
        PY_FOREACH_FUNC_EVENT(CASE)
24
0
        #undef CASE
25
0
    }
26
0
    Py_UNREACHABLE();
27
0
}
28
29
static void
30
notify_func_watchers(PyInterpreterState *interp, PyFunction_WatchEvent event,
31
                     PyFunctionObject *func, PyObject *new_value)
32
0
{
33
0
    uint8_t bits = interp->active_func_watchers;
34
0
    int i = 0;
35
0
    while (bits) {
36
0
        assert(i < FUNC_MAX_WATCHERS);
37
0
        if (bits & 1) {
38
0
            PyFunction_WatchCallback cb = interp->func_watchers[i];
39
            // callback must be non-null if the watcher bit is set
40
0
            assert(cb != NULL);
41
0
            if (cb(event, func, new_value) < 0) {
42
0
                PyErr_FormatUnraisable(
43
0
                    "Exception ignored in %s watcher callback for function %U at %p",
44
0
                    func_event_name(event),
45
0
                    FT_ATOMIC_LOAD_PTR_ACQUIRE(func->func_qualname), func);
46
0
            }
47
0
        }
48
0
        i++;
49
0
        bits >>= 1;
50
0
    }
51
0
}
52
53
static inline void
54
handle_func_event(PyFunction_WatchEvent event, PyFunctionObject *func,
55
                  PyObject *new_value)
56
30.9M
{
57
30.9M
    assert(Py_REFCNT(func) > 0);
58
30.9M
    PyInterpreterState *interp = _PyInterpreterState_GET();
59
30.9M
    assert(interp->_initialized);
60
30.9M
    if (interp->active_func_watchers) {
61
0
        notify_func_watchers(interp, event, func, new_value);
62
0
    }
63
30.9M
    switch (event) {
64
254
        case PyFunction_EVENT_MODIFY_CODE:
65
544
        case PyFunction_EVENT_MODIFY_DEFAULTS:
66
696
        case PyFunction_EVENT_MODIFY_KWDEFAULTS:
67
3.29k
        case PyFunction_EVENT_MODIFY_QUALNAME:
68
#if _Py_TIER2
69
            // Note: we only invalidate JIT code if a function version changes.
70
            // Not when the function is deallocated.
71
            // Function deallocation occurs frequently (think: lambdas),
72
            // so we want to minimize dependency invalidation there.
73
            _Py_Executors_InvalidateDependency(interp, func, 1);
74
#endif
75
3.29k
            RARE_EVENT_INTERP_INC(interp, func_modification);
76
3.29k
            break;
77
30.9M
        default:
78
30.9M
            break;
79
30.9M
    }
80
30.9M
}
81
82
int
83
PyFunction_AddWatcher(PyFunction_WatchCallback callback)
84
0
{
85
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
86
0
    assert(interp->_initialized);
87
0
    for (int i = 0; i < FUNC_MAX_WATCHERS; i++) {
88
0
        if (interp->func_watchers[i] == NULL) {
89
0
            interp->func_watchers[i] = callback;
90
0
            interp->active_func_watchers |= (1 << i);
91
0
            return i;
92
0
        }
93
0
    }
94
0
    PyErr_SetString(PyExc_RuntimeError, "no more func watcher IDs available");
95
0
    return -1;
96
0
}
97
98
int
99
PyFunction_ClearWatcher(int watcher_id)
100
0
{
101
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
102
0
    if (watcher_id < 0 || watcher_id >= FUNC_MAX_WATCHERS) {
103
0
        PyErr_Format(PyExc_ValueError, "invalid func watcher ID %d",
104
0
                     watcher_id);
105
0
        return -1;
106
0
    }
107
0
    if (!interp->func_watchers[watcher_id]) {
108
0
        PyErr_Format(PyExc_ValueError, "no func watcher set for ID %d",
109
0
                     watcher_id);
110
0
        return -1;
111
0
    }
112
0
    interp->func_watchers[watcher_id] = NULL;
113
0
    interp->active_func_watchers &= ~(1 << watcher_id);
114
0
    return 0;
115
0
}
116
PyFunctionObject *
117
_PyFunction_FromConstructor(PyFrameConstructor *constr)
118
4.20k
{
119
4.20k
    PyObject *module;
120
4.20k
    if (PyDict_GetItemRef(constr->fc_globals, &_Py_ID(__name__), &module) < 0) {
121
0
        return NULL;
122
0
    }
123
124
4.20k
    PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
125
4.20k
    if (op == NULL) {
126
0
        Py_XDECREF(module);
127
0
        return NULL;
128
0
    }
129
4.20k
    _Py_INCREF_DICT(constr->fc_globals);
130
4.20k
    op->func_globals = constr->fc_globals;
131
4.20k
    _Py_INCREF_BUILTINS(constr->fc_builtins);
132
4.20k
    op->func_builtins = constr->fc_builtins;
133
4.20k
    op->func_name = Py_NewRef(constr->fc_name);
134
4.20k
    op->func_qualname = Py_NewRef(constr->fc_qualname);
135
4.20k
    _Py_INCREF_CODE((PyCodeObject *)constr->fc_code);
136
4.20k
    op->func_code = constr->fc_code;
137
4.20k
    op->func_defaults = Py_XNewRef(constr->fc_defaults);
138
4.20k
    op->func_kwdefaults = Py_XNewRef(constr->fc_kwdefaults);
139
4.20k
    op->func_closure = Py_XNewRef(constr->fc_closure);
140
4.20k
    op->func_doc = Py_NewRef(Py_None);
141
4.20k
    op->func_dict = NULL;
142
4.20k
    op->func_weakreflist = NULL;
143
4.20k
    op->func_module = module;
144
4.20k
    op->func_annotations = NULL;
145
4.20k
    op->func_annotate = NULL;
146
4.20k
    op->func_typeparams = NULL;
147
4.20k
    op->vectorcall = _PyFunction_Vectorcall;
148
4.20k
    op->func_version = FUNC_VERSION_UNSET;
149
    // NOTE: functions created via FrameConstructor do not use deferred
150
    // reference counting because they are typically not part of cycles
151
    // nor accessed by multiple threads.
152
4.20k
    _PyObject_GC_TRACK(op);
153
4.20k
    handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
154
4.20k
    return op;
155
4.20k
}
156
157
PyObject *
158
PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
159
15.4M
{
160
15.4M
    assert(globals != NULL);
161
15.4M
    assert(PyAnyDict_Check(globals));
162
15.4M
    _Py_INCREF_DICT(globals);
163
164
15.4M
    PyCodeObject *code_obj = (PyCodeObject *)code;
165
15.4M
    _Py_INCREF_CODE(code_obj);
166
167
15.4M
    assert(code_obj->co_name != NULL);
168
15.4M
    PyObject *name = Py_NewRef(code_obj->co_name);
169
170
15.4M
    if (!qualname) {
171
15.4M
        qualname = code_obj->co_qualname;
172
15.4M
    }
173
15.4M
    assert(qualname != NULL);
174
15.4M
    Py_INCREF(qualname);
175
176
15.4M
    PyObject *consts = code_obj->co_consts;
177
15.4M
    assert(PyTuple_Check(consts));
178
15.4M
    PyObject *doc;
179
15.4M
    if (code_obj->co_flags & CO_HAS_DOCSTRING) {
180
52.5k
        assert(PyTuple_Size(consts) >= 1);
181
52.5k
        doc = PyTuple_GetItem(consts, 0);
182
52.5k
        if (!PyUnicode_Check(doc)) {
183
0
            doc = Py_None;
184
0
        }
185
52.5k
    }
186
15.4M
    else {
187
15.4M
        doc = Py_None;
188
15.4M
    }
189
15.4M
    Py_INCREF(doc);
190
191
    // __module__: Use globals['__name__'] if it exists, or NULL.
192
15.4M
    PyObject *module;
193
15.4M
    PyObject *builtins = NULL;
194
15.4M
    if (PyDict_GetItemRef(globals, &_Py_ID(__name__), &module) < 0) {
195
0
        goto error;
196
0
    }
197
198
15.4M
    builtins = _PyDict_LoadBuiltinsFromGlobals(globals);
199
15.4M
    if (builtins == NULL) {
200
0
        goto error;
201
0
    }
202
203
15.4M
    PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
204
15.4M
    if (op == NULL) {
205
0
        goto error;
206
0
    }
207
    /* Note: No failures from this point on, since func_dealloc() does not
208
       expect a partially-created object. */
209
210
15.4M
    op->func_globals = globals;
211
15.4M
    op->func_builtins = builtins;
212
15.4M
    op->func_name = name;
213
15.4M
    op->func_qualname = qualname;
214
15.4M
    op->func_code = (PyObject*)code_obj;
215
15.4M
    op->func_defaults = NULL;    // No default positional arguments
216
15.4M
    op->func_kwdefaults = NULL;  // No default keyword arguments
217
15.4M
    op->func_closure = NULL;
218
15.4M
    op->func_doc = doc;
219
15.4M
    op->func_dict = NULL;
220
15.4M
    op->func_weakreflist = NULL;
221
15.4M
    op->func_module = module;
222
15.4M
    op->func_annotations = NULL;
223
15.4M
    op->func_annotate = NULL;
224
15.4M
    op->func_typeparams = NULL;
225
15.4M
    op->vectorcall = _PyFunction_Vectorcall;
226
15.4M
    op->func_version = FUNC_VERSION_UNSET;
227
15.4M
    if (((code_obj->co_flags & CO_NESTED) == 0) ||
228
15.4M
        (code_obj->co_flags & CO_METHOD)) {
229
        // Use deferred reference counting for top-level functions, but not
230
        // nested functions because they are more likely to capture variables,
231
        // which makes prompt deallocation more important.
232
        //
233
        // Nested methods (functions defined in class scope) are also deferred,
234
        // since they will likely be cleaned up by GC anyway.
235
89.2k
        _PyObject_SetDeferredRefcount((PyObject *)op);
236
89.2k
    }
237
15.4M
    _PyObject_GC_TRACK(op);
238
15.4M
    handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
239
15.4M
    return (PyObject *)op;
240
241
0
error:
242
0
    Py_DECREF(globals);
243
0
    Py_DECREF(code_obj);
244
0
    Py_DECREF(name);
245
0
    Py_DECREF(qualname);
246
0
    Py_DECREF(doc);
247
0
    Py_XDECREF(module);
248
0
    Py_XDECREF(builtins);
249
0
    return NULL;
250
15.4M
}
251
252
/*
253
(This is purely internal documentation. There are no public APIs here.)
254
255
Function (and code) versions
256
----------------------------
257
258
The Tier 1 specializer generates CALL variants that can be invalidated
259
by changes to critical function attributes:
260
261
- __code__
262
- __defaults__
263
- __kwdefaults__
264
- __closure__
265
266
For this purpose function objects have a 32-bit func_version member
267
that the specializer writes to the specialized instruction's inline
268
cache and which is checked by a guard on the specialized instructions.
269
270
The MAKE_FUNCTION bytecode sets func_version from the code object's
271
co_version field.  The latter is initialized from a counter in the
272
interpreter state (interp->func_state.next_version) and never changes.
273
When this counter overflows, it remains zero and the specializer loses
274
the ability to specialize calls to new functions.
275
276
The func_version is reset to zero when any of the critical attributes
277
is modified; after this point the specializer will no longer specialize
278
calls to this function, and the guard will always fail.
279
280
The function and code version cache
281
-----------------------------------
282
283
The Tier 2 optimizer now has a problem, since it needs to find the
284
function and code objects given only the version number from the inline
285
cache.  Our solution is to maintain a cache mapping version numbers to
286
function and code objects.  To limit the cache size we could hash
287
the version number, but for now we simply use it modulo the table size.
288
289
There are some corner cases (e.g. generator expressions) where we will
290
be unable to find the function object in the cache but we can still
291
find the code object.  For this reason the cache stores both the
292
function object and the code object.
293
294
The cache doesn't contain strong references; cache entries are
295
invalidated whenever the function or code object is deallocated.
296
297
Invariants
298
----------
299
300
These should hold at any time except when one of the cache-mutating
301
functions is running.
302
303
- For any slot s at index i:
304
    - s->func == NULL or s->func->func_version % FUNC_VERSION_CACHE_SIZE == i
305
    - s->code == NULL or s->code->co_version % FUNC_VERSION_CACHE_SIZE == i
306
    if s->func != NULL, then s->func->func_code == s->code
307
308
*/
309
310
#ifndef Py_GIL_DISABLED
311
static inline struct _func_version_cache_item *
312
get_cache_item(PyInterpreterState *interp, uint32_t version)
313
30.9M
{
314
30.9M
    return interp->func_state.func_version_cache +
315
30.9M
           (version % FUNC_VERSION_CACHE_SIZE);
316
30.9M
}
317
#endif
318
319
void
320
_PyFunction_SetVersion(PyFunctionObject *func, uint32_t version)
321
15.4M
{
322
15.4M
    assert(func->func_version == FUNC_VERSION_UNSET);
323
15.4M
    assert(version >= FUNC_VERSION_FIRST_VALID);
324
    // This should only be called from MAKE_FUNCTION. No code is specialized
325
    // based on the version, so we do not need to stop the world to set it.
326
15.4M
    func->func_version = version;
327
15.4M
#ifndef Py_GIL_DISABLED
328
15.4M
    PyInterpreterState *interp = _PyInterpreterState_GET();
329
15.4M
    struct _func_version_cache_item *slot = get_cache_item(interp, version);
330
15.4M
    slot->func = func;
331
15.4M
    slot->code = func->func_code;
332
15.4M
#endif
333
15.4M
}
334
335
static void
336
func_clear_version(PyInterpreterState *interp, PyFunctionObject *func)
337
15.4M
{
338
15.4M
    if (func->func_version < FUNC_VERSION_FIRST_VALID) {
339
        // Version was never set or has already been cleared.
340
26.2k
        return;
341
26.2k
    }
342
15.4M
#ifndef Py_GIL_DISABLED
343
15.4M
    struct _func_version_cache_item *slot =
344
15.4M
        get_cache_item(interp, func->func_version);
345
15.4M
    if (slot->func == func) {
346
9.37M
        slot->func = NULL;
347
        // Leave slot->code alone, there may be use for it.
348
9.37M
    }
349
15.4M
#endif
350
15.4M
    func->func_version = FUNC_VERSION_CLEARED;
351
15.4M
}
352
353
void
354
_PyFunction_ClearCodeByVersion(uint32_t version)
355
17.9k
{
356
17.9k
#ifndef Py_GIL_DISABLED
357
17.9k
    PyInterpreterState *interp = _PyInterpreterState_GET();
358
17.9k
    struct _func_version_cache_item *slot = get_cache_item(interp, version);
359
17.9k
    if (slot->code) {
360
12.8k
        assert(PyCode_Check(slot->code));
361
12.8k
        PyCodeObject *code = (PyCodeObject *)slot->code;
362
12.8k
        if (code->co_version == version) {
363
12.0k
            slot->code = NULL;
364
12.0k
            slot->func = NULL;
365
12.0k
        }
366
12.8k
    }
367
17.9k
#endif
368
17.9k
}
369
370
uint32_t
371
_PyFunction_GetVersionForCurrentState(PyFunctionObject *func)
372
268k
{
373
268k
    return func->func_version;
374
268k
}
375
376
PyObject *
377
PyFunction_New(PyObject *code, PyObject *globals)
378
15.4M
{
379
15.4M
    return PyFunction_NewWithQualName(code, globals, NULL);
380
15.4M
}
381
382
PyObject *
383
PyFunction_GetCode(PyObject *op)
384
0
{
385
0
    if (!PyFunction_Check(op)) {
386
0
        PyErr_BadInternalCall();
387
0
        return NULL;
388
0
    }
389
0
    return ((PyFunctionObject *) op) -> func_code;
390
0
}
391
392
PyObject *
393
PyFunction_GetGlobals(PyObject *op)
394
0
{
395
0
    if (!PyFunction_Check(op)) {
396
0
        PyErr_BadInternalCall();
397
0
        return NULL;
398
0
    }
399
0
    return ((PyFunctionObject *) op) -> func_globals;
400
0
}
401
402
PyObject *
403
PyFunction_GetModule(PyObject *op)
404
512
{
405
512
    if (!PyFunction_Check(op)) {
406
0
        PyErr_BadInternalCall();
407
0
        return NULL;
408
0
    }
409
512
    return PyFunction_GET_MODULE(op);
410
512
}
411
412
PyObject *
413
PyFunction_GetDefaults(PyObject *op)
414
0
{
415
0
    if (!PyFunction_Check(op)) {
416
0
        PyErr_BadInternalCall();
417
0
        return NULL;
418
0
    }
419
0
    return ((PyFunctionObject *) op) -> func_defaults;
420
0
}
421
422
int
423
PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
424
0
{
425
0
    if (!PyFunction_Check(op)) {
426
0
        PyErr_BadInternalCall();
427
0
        return -1;
428
0
    }
429
0
    if (defaults == Py_None)
430
0
        defaults = NULL;
431
0
    else if (defaults && PyTuple_Check(defaults)) {
432
0
        Py_INCREF(defaults);
433
0
    }
434
0
    else {
435
0
        PyErr_SetString(PyExc_SystemError, "non-tuple default args");
436
0
        return -1;
437
0
    }
438
0
    PyFunctionObject *func = (PyFunctionObject *)op;
439
0
    handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS, func, defaults);
440
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
441
0
    _PyEval_StopTheWorld(interp);
442
0
    func_clear_version(interp, func);
443
0
    PyObject *old_defaults = func->func_defaults;
444
0
    func->func_defaults = defaults;
445
0
    _PyEval_StartTheWorld(interp);
446
0
    Py_XDECREF(old_defaults);
447
0
    return 0;
448
0
}
449
450
void
451
PyFunction_SetVectorcall(PyFunctionObject *func, vectorcallfunc vectorcall)
452
0
{
453
0
    assert(func != NULL);
454
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
455
0
    _PyEval_StopTheWorld(interp);
456
0
    func_clear_version(interp, func);
457
0
    func->vectorcall = vectorcall;
458
0
    _PyEval_StartTheWorld(interp);
459
0
}
460
461
PyObject *
462
PyFunction_GetKwDefaults(PyObject *op)
463
0
{
464
0
    if (!PyFunction_Check(op)) {
465
0
        PyErr_BadInternalCall();
466
0
        return NULL;
467
0
    }
468
0
    return ((PyFunctionObject *) op) -> func_kwdefaults;
469
0
}
470
471
int
472
PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults)
473
0
{
474
0
    if (!PyFunction_Check(op)) {
475
0
        PyErr_BadInternalCall();
476
0
        return -1;
477
0
    }
478
0
    if (defaults == Py_None)
479
0
        defaults = NULL;
480
0
    else if (defaults && PyDict_Check(defaults)) {
481
0
        Py_INCREF(defaults);
482
0
    }
483
0
    else {
484
0
        PyErr_SetString(PyExc_SystemError,
485
0
                        "non-dict keyword only default args");
486
0
        return -1;
487
0
    }
488
0
    PyFunctionObject *func = (PyFunctionObject *)op;
489
0
    handle_func_event(PyFunction_EVENT_MODIFY_KWDEFAULTS, func, defaults);
490
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
491
0
    _PyEval_StopTheWorld(interp);
492
0
    func_clear_version(interp, func);
493
0
    PyObject *old_kwdefaults = func->func_kwdefaults;
494
0
    func->func_kwdefaults = defaults;
495
0
    _PyEval_StartTheWorld(interp);
496
0
    Py_XDECREF(old_kwdefaults);
497
0
    return 0;
498
0
}
499
500
PyObject *
501
PyFunction_GetClosure(PyObject *op)
502
0
{
503
0
    if (!PyFunction_Check(op)) {
504
0
        PyErr_BadInternalCall();
505
0
        return NULL;
506
0
    }
507
0
    return ((PyFunctionObject *) op) -> func_closure;
508
0
}
509
510
int
511
PyFunction_SetClosure(PyObject *op, PyObject *closure)
512
0
{
513
0
    if (!PyFunction_Check(op)) {
514
0
        PyErr_BadInternalCall();
515
0
        return -1;
516
0
    }
517
0
    if (closure == Py_None)
518
0
        closure = NULL;
519
0
    else if (PyTuple_Check(closure)) {
520
0
        Py_INCREF(closure);
521
0
    }
522
0
    else {
523
0
        PyErr_Format(PyExc_SystemError,
524
0
                     "expected tuple for closure, got '%.100s'",
525
0
                     Py_TYPE(closure)->tp_name);
526
0
        return -1;
527
0
    }
528
0
    PyFunctionObject *func = (PyFunctionObject *)op;
529
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
530
0
    _PyEval_StopTheWorld(interp);
531
0
    func_clear_version(interp, func);
532
0
    PyObject *old_closure = func->func_closure;
533
0
    func->func_closure = closure;
534
0
    _PyEval_StartTheWorld(interp);
535
0
    Py_XDECREF(old_closure);
536
0
    return 0;
537
0
}
538
539
static void
540
func_set_annotations_and_annotate(PyFunctionObject *op, PyObject *annotations,
541
                                  PyObject *annotate)
542
671
{
543
671
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
544
    // Care is needed, finalizers can run when references are dropped.  Store
545
    // both new values before dropping references to the old.
546
671
    PyObject *old_annotations = op->func_annotations;
547
671
    PyObject *old_annotate = op->func_annotate;
548
671
    FT_ATOMIC_STORE_PTR_RELEASE(op->func_annotations, annotations);
549
671
    FT_ATOMIC_STORE_PTR_RELEASE(op->func_annotate, annotate);
550
671
    if (old_annotations != NULL && !_Py_IsImmortal(old_annotations)) {
551
230
        _PyObject_XDecRefDelayed(old_annotations);
552
230
    }
553
671
    if (old_annotate != NULL && !_Py_IsImmortal(old_annotate)) {
554
8
        _PyObject_XDecRefDelayed(old_annotate);
555
8
    }
556
671
}
557
558
static PyObject *
559
func_get_annotation_dict(PyFunctionObject *op)
560
574
{
561
574
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
562
574
    if (op->func_annotations == NULL) {
563
248
        PyObject *annotate = op->func_annotate;
564
248
        if (annotate == NULL || !PyCallable_Check(annotate)) {
565
0
            Py_RETURN_NONE;
566
0
        }
567
        // Calling __annotate__ can run arbitrary code which may replace
568
        // func_annotate or func_annotations, either directly or from another
569
        // thread while the critical section is suspended.  Keep the callable
570
        // alive during the call.
571
248
        Py_INCREF(annotate);
572
248
        PyObject *one = _PyLong_GetOne();
573
248
        PyObject *ann_dict = _PyObject_CallOneArg(annotate, one);
574
248
        Py_DECREF(annotate);
575
248
        if (ann_dict == NULL) {
576
0
            return NULL;
577
0
        }
578
248
        if (!PyDict_Check(ann_dict)) {
579
0
            PyErr_Format(PyExc_TypeError,
580
0
                         "__annotate__() must return a dict, not %T",
581
0
                         ann_dict);
582
0
            Py_DECREF(ann_dict);
583
0
            return NULL;
584
0
        }
585
248
        if (op->func_annotations != NULL) {
586
            // Annotations were set during the call, keep them.
587
0
            Py_DECREF(ann_dict);
588
0
            assert(PyDict_Check(op->func_annotations));
589
0
            return op->func_annotations;
590
0
        }
591
248
        _PyObject_XSetRefDelayed(&op->func_annotations, ann_dict);
592
248
        return ann_dict;
593
248
    }
594
326
    if (PyTuple_CheckExact(op->func_annotations)) {
595
        // Keep the tuple alive while building the dict, since it can be
596
        // replaced if the critical section is suspended.
597
0
        PyObject *ann_tuple = Py_NewRef(op->func_annotations);
598
0
        PyObject *ann_dict = PyDict_New();
599
0
        if (ann_dict == NULL) {
600
0
            Py_DECREF(ann_tuple);
601
0
            return NULL;
602
0
        }
603
604
0
        assert(PyTuple_GET_SIZE(ann_tuple) % 2 == 0);
605
606
0
        for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(ann_tuple); i += 2) {
607
0
            int err = PyDict_SetItem(ann_dict,
608
0
                                     PyTuple_GET_ITEM(ann_tuple, i),
609
0
                                     PyTuple_GET_ITEM(ann_tuple, i + 1));
610
611
0
            if (err < 0) {
612
0
                Py_DECREF(ann_dict);
613
0
                Py_DECREF(ann_tuple);
614
0
                return NULL;
615
0
            }
616
0
        }
617
0
        _PyObject_XSetRefDelayed(&op->func_annotations, ann_dict);
618
0
        _PyObject_XDecRefDelayed(ann_tuple);
619
0
    }
620
326
    assert(PyDict_Check(op->func_annotations));
621
326
    return op->func_annotations;
622
326
}
623
624
PyObject *
625
PyFunction_GetAnnotations(PyObject *op)
626
0
{
627
0
    if (!PyFunction_Check(op)) {
628
0
        PyErr_BadInternalCall();
629
0
        return NULL;
630
0
    }
631
0
    PyObject *d;
632
0
    Py_BEGIN_CRITICAL_SECTION(op);
633
0
    d = func_get_annotation_dict((PyFunctionObject *)op);
634
0
    Py_END_CRITICAL_SECTION();
635
0
    return d;
636
0
}
637
638
int
639
PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)
640
0
{
641
0
    if (!PyFunction_Check(op)) {
642
0
        PyErr_BadInternalCall();
643
0
        return -1;
644
0
    }
645
0
    if (annotations == Py_None)
646
0
        annotations = NULL;
647
0
    else if (annotations && PyDict_Check(annotations)) {
648
0
        Py_INCREF(annotations);
649
0
    }
650
0
    else {
651
0
        PyErr_SetString(PyExc_SystemError,
652
0
                        "non-dict annotations");
653
0
        return -1;
654
0
    }
655
0
    PyFunctionObject *func = (PyFunctionObject *)op;
656
0
    Py_BEGIN_CRITICAL_SECTION(func);
657
0
    func_set_annotations_and_annotate(func, annotations, NULL);
658
0
    Py_END_CRITICAL_SECTION();
659
0
    return 0;
660
0
}
661
662
/* Methods */
663
664
#define OFF(x) offsetof(PyFunctionObject, x)
665
666
static PyMemberDef func_memberlist[] = {
667
    {"__closure__",   _Py_T_OBJECT,     OFF(func_closure), Py_READONLY},
668
    {"__globals__",   _Py_T_OBJECT,     OFF(func_globals), Py_READONLY},
669
    {"__builtins__",  _Py_T_OBJECT,     OFF(func_builtins), Py_READONLY},
670
    {NULL}  /* Sentinel */
671
};
672
673
/*[clinic input]
674
class function "PyFunctionObject *" "&PyFunction_Type"
675
[clinic start generated code]*/
676
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=70af9c90aa2e71b0]*/
677
678
#include "clinic/funcobject.c.h"
679
680
static PyObject *
681
func_get_code(PyObject *self, void *Py_UNUSED(ignored))
682
153k
{
683
153k
    PyFunctionObject *op = _PyFunction_CAST(self);
684
153k
    if (PySys_Audit("object.__getattr__", "Os", op, "__code__") < 0) {
685
0
        return NULL;
686
0
    }
687
688
153k
    return Py_NewRef(op->func_code);
689
153k
}
690
691
static int
692
func_set_code(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
693
254
{
694
254
    PyFunctionObject *op = _PyFunction_CAST(self);
695
696
    /* Not legal to del f.func_code or to set it to anything
697
     * other than a code object. */
698
254
    if (value == NULL || !PyCode_Check(value)) {
699
0
        PyErr_SetString(PyExc_TypeError,
700
0
                        "__code__ must be set to a code object");
701
0
        return -1;
702
0
    }
703
704
254
    if (PySys_Audit("object.__setattr__", "OsO",
705
254
                    op, "__code__", value) < 0) {
706
0
        return -1;
707
0
    }
708
709
254
    int nfree = ((PyCodeObject *)value)->co_nfreevars;
710
254
    Py_ssize_t nclosure = (op->func_closure == NULL ? 0 :
711
254
                                        PyTuple_GET_SIZE(op->func_closure));
712
254
    if (nclosure != nfree) {
713
0
        PyObject *name = FT_ATOMIC_LOAD_PTR_ACQUIRE(op->func_name);
714
0
        PyErr_Format(PyExc_ValueError,
715
0
                     "%U() requires a code object with %zd free vars,"
716
0
                     " not %d",
717
0
                     name, nclosure, nfree);
718
0
        return -1;
719
0
    }
720
721
254
    PyObject *func_code = PyFunction_GET_CODE(op);
722
254
    int old_flags = ((PyCodeObject *)func_code)->co_flags;
723
254
    int new_flags = ((PyCodeObject *)value)->co_flags;
724
254
    int mask = CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR;
725
254
    if ((old_flags & mask) != (new_flags & mask)) {
726
0
        if (PyErr_Warn(PyExc_DeprecationWarning,
727
0
            "Assigning a code object of non-matching type is deprecated "
728
0
            "(e.g., from a generator to a plain function)") < 0)
729
0
        {
730
0
            return -1;
731
0
        }
732
0
    }
733
734
254
    handle_func_event(PyFunction_EVENT_MODIFY_CODE, op, value);
735
254
    PyInterpreterState *interp = _PyInterpreterState_GET();
736
254
    _PyEval_StopTheWorld(interp);
737
254
    func_clear_version(interp, op);
738
254
    PyObject *old_code = op->func_code;
739
254
    op->func_code = Py_NewRef(value);
740
254
    _PyEval_StartTheWorld(interp);
741
254
    Py_XDECREF(old_code);
742
254
    return 0;
743
254
}
744
745
static PyObject *
746
func_get_name(PyObject *self, void *Py_UNUSED(ignored))
747
52.1k
{
748
52.1k
    PyFunctionObject *op = _PyFunction_CAST(self);
749
52.1k
    PyObject *name = FT_ATOMIC_LOAD_PTR_ACQUIRE(op->func_name);
750
52.1k
    return Py_NewRef(name);
751
52.1k
}
752
753
static int
754
func_set_name(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
755
1.62k
{
756
1.62k
    PyFunctionObject *op = _PyFunction_CAST(self);
757
    /* Not legal to del f.func_name or to set it to anything
758
     * other than a string object. */
759
1.62k
    if (value == NULL || !PyUnicode_Check(value)) {
760
0
        PyErr_SetString(PyExc_TypeError,
761
0
                        "__name__ must be set to a string object");
762
0
        return -1;
763
0
    }
764
1.62k
    Py_BEGIN_CRITICAL_SECTION(op);
765
1.62k
    _PyObject_XSetRefDelayed(&op->func_name, Py_NewRef(value));
766
1.62k
    Py_END_CRITICAL_SECTION();
767
1.62k
    return 0;
768
1.62k
}
769
770
static PyObject *
771
func_get_qualname(PyObject *self, void *Py_UNUSED(ignored))
772
5.98k
{
773
5.98k
    PyFunctionObject *op = _PyFunction_CAST(self);
774
5.98k
    PyObject *qualname = FT_ATOMIC_LOAD_PTR_ACQUIRE(op->func_qualname);
775
5.98k
    return Py_NewRef(qualname);
776
5.98k
}
777
778
static int
779
func_set_qualname(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
780
2.60k
{
781
2.60k
    PyFunctionObject *op = _PyFunction_CAST(self);
782
    /* Not legal to del f.__qualname__ or to set it to anything
783
     * other than a string object. */
784
2.60k
    if (value == NULL || !PyUnicode_Check(value)) {
785
0
        PyErr_SetString(PyExc_TypeError,
786
0
                        "__qualname__ must be set to a string object");
787
0
        return -1;
788
0
    }
789
2.60k
    handle_func_event(PyFunction_EVENT_MODIFY_QUALNAME, (PyFunctionObject *) op, value);
790
2.60k
    Py_BEGIN_CRITICAL_SECTION(op);
791
2.60k
    _PyObject_XSetRefDelayed(&op->func_qualname, Py_NewRef(value));
792
2.60k
    Py_END_CRITICAL_SECTION();
793
2.60k
    return 0;
794
2.60k
}
795
796
static PyObject *
797
func_get_doc(PyObject *self, void *Py_UNUSED(ignored))
798
153k
{
799
153k
    PyFunctionObject *op = _PyFunction_CAST(self);
800
153k
    PyObject *doc = FT_ATOMIC_LOAD_PTR_ACQUIRE(op->func_doc);
801
153k
    if (doc == NULL) {
802
0
        doc = Py_None;
803
0
    }
804
153k
    return Py_NewRef(doc);
805
153k
}
806
807
static int
808
func_set_doc(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
809
2.32k
{
810
    /* Legal to del f.__doc__ or to set it to any object. */
811
2.32k
    PyFunctionObject *op = _PyFunction_CAST(self);
812
2.32k
    Py_BEGIN_CRITICAL_SECTION(op);
813
2.32k
    _PyObject_XSetRefDelayed(&op->func_doc, Py_XNewRef(value));
814
2.32k
    Py_END_CRITICAL_SECTION();
815
2.32k
    return 0;
816
2.32k
}
817
818
static PyObject *
819
func_get_module(PyObject *self, void *Py_UNUSED(ignored))
820
6.39k
{
821
6.39k
    PyFunctionObject *op = _PyFunction_CAST(self);
822
6.39k
    PyObject *module = FT_ATOMIC_LOAD_PTR_ACQUIRE(op->func_module);
823
6.39k
    if (module == NULL) {
824
0
        module = Py_None;
825
0
    }
826
6.39k
    return Py_NewRef(module);
827
6.39k
}
828
829
static int
830
func_set_module(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
831
1.34k
{
832
    /* Legal to del f.__module__ or to set it to any object. */
833
1.34k
    PyFunctionObject *op = _PyFunction_CAST(self);
834
1.34k
    Py_BEGIN_CRITICAL_SECTION(op);
835
1.34k
    _PyObject_XSetRefDelayed(&op->func_module, Py_XNewRef(value));
836
1.34k
    Py_END_CRITICAL_SECTION();
837
1.34k
    return 0;
838
1.34k
}
839
840
static PyObject *
841
func_get_defaults(PyObject *self, void *Py_UNUSED(ignored))
842
21.8k
{
843
21.8k
    PyFunctionObject *op = _PyFunction_CAST(self);
844
21.8k
    if (PySys_Audit("object.__getattr__", "Os", op, "__defaults__") < 0) {
845
0
        return NULL;
846
0
    }
847
21.8k
    if (op->func_defaults == NULL) {
848
21.7k
        Py_RETURN_NONE;
849
21.7k
    }
850
136
    return Py_NewRef(op->func_defaults);
851
21.8k
}
852
853
static int
854
func_set_defaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
855
290
{
856
    /* Legal to del f.func_defaults.
857
     * Can only set func_defaults to NULL or a tuple. */
858
290
    PyFunctionObject *op = _PyFunction_CAST(self);
859
290
    if (value == Py_None)
860
0
        value = NULL;
861
290
    if (value != NULL && !PyTuple_Check(value)) {
862
0
        PyErr_SetString(PyExc_TypeError,
863
0
                        "__defaults__ must be set to a tuple object");
864
0
        return -1;
865
0
    }
866
290
    if (value) {
867
290
        if (PySys_Audit("object.__setattr__", "OsO",
868
290
                        op, "__defaults__", value) < 0) {
869
0
            return -1;
870
0
        }
871
290
    } else if (PySys_Audit("object.__delattr__", "Os",
872
0
                           op, "__defaults__") < 0) {
873
0
        return -1;
874
0
    }
875
876
290
    handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS, op, value);
877
290
    PyInterpreterState *interp = _PyInterpreterState_GET();
878
290
    _PyEval_StopTheWorld(interp);
879
290
    func_clear_version(interp, op);
880
290
    PyObject *old_defaults = op->func_defaults;
881
290
    op->func_defaults = Py_XNewRef(value);
882
290
    _PyEval_StartTheWorld(interp);
883
290
    Py_XDECREF(old_defaults);
884
290
    return 0;
885
290
}
886
887
static PyObject *
888
func_get_kwdefaults(PyObject *self, void *Py_UNUSED(ignored))
889
21.8k
{
890
21.8k
    PyFunctionObject *op = _PyFunction_CAST(self);
891
21.8k
    if (PySys_Audit("object.__getattr__", "Os",
892
21.8k
                    op, "__kwdefaults__") < 0) {
893
0
        return NULL;
894
0
    }
895
21.8k
    if (op->func_kwdefaults == NULL) {
896
21.7k
        Py_RETURN_NONE;
897
21.7k
    }
898
160
    return Py_NewRef(op->func_kwdefaults);
899
21.8k
}
900
901
static int
902
func_set_kwdefaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
903
152
{
904
152
    PyFunctionObject *op = _PyFunction_CAST(self);
905
152
    if (value == Py_None)
906
0
        value = NULL;
907
    /* Legal to del f.func_kwdefaults.
908
     * Can only set func_kwdefaults to NULL or a dict. */
909
152
    if (value != NULL && !PyDict_Check(value)) {
910
0
        PyErr_SetString(PyExc_TypeError,
911
0
            "__kwdefaults__ must be set to a dict object");
912
0
        return -1;
913
0
    }
914
152
    if (value) {
915
152
        if (PySys_Audit("object.__setattr__", "OsO",
916
152
                        op, "__kwdefaults__", value) < 0) {
917
0
            return -1;
918
0
        }
919
152
    } else if (PySys_Audit("object.__delattr__", "Os",
920
0
                           op, "__kwdefaults__") < 0) {
921
0
        return -1;
922
0
    }
923
924
152
    handle_func_event(PyFunction_EVENT_MODIFY_KWDEFAULTS, op, value);
925
152
    PyInterpreterState *interp = _PyInterpreterState_GET();
926
152
    _PyEval_StopTheWorld(interp);
927
152
    func_clear_version(interp, op);
928
152
    PyObject *old_kwdefaults = op->func_kwdefaults;
929
152
    op->func_kwdefaults = Py_XNewRef(value);
930
152
    _PyEval_StartTheWorld(interp);
931
152
    Py_XDECREF(old_kwdefaults);
932
152
    return 0;
933
152
}
934
935
/*[clinic input]
936
@critical_section
937
@getter
938
function.__annotate__
939
940
Get the code object for a function.
941
[clinic start generated code]*/
942
943
static PyObject *
944
function___annotate___get_impl(PyFunctionObject *self)
945
/*[clinic end generated code: output=5ec7219ff2bda9e6 input=7f3db11e3c3329f3]*/
946
1.03k
{
947
1.03k
    if (self->func_annotate == NULL) {
948
582
        Py_RETURN_NONE;
949
582
    }
950
451
    return Py_NewRef(self->func_annotate);
951
1.03k
}
952
953
/*[clinic input]
954
@critical_section
955
@setter
956
function.__annotate__
957
[clinic start generated code]*/
958
959
static int
960
function___annotate___set_impl(PyFunctionObject *self, PyObject *value)
961
/*[clinic end generated code: output=05b7dfc07ada66cd input=eb6225e358d97448]*/
962
780
{
963
780
    if (Py_IsNone(value)) {
964
371
        _PyObject_XSetRefDelayed(&self->func_annotate, Py_NewRef(value));
965
371
        return 0;
966
371
    }
967
409
    else if (PyCallable_Check(value)) {
968
409
        func_set_annotations_and_annotate(self, NULL, Py_NewRef(value));
969
409
        return 0;
970
409
    }
971
0
    else {
972
0
        PyErr_SetString(PyExc_TypeError,
973
0
            "__annotate__ must be callable or None");
974
0
        return -1;
975
0
    }
976
780
}
977
978
/*[clinic input]
979
@critical_section
980
@getter
981
function.__annotations__
982
983
Dict of annotations in a function object.
984
[clinic start generated code]*/
985
986
static PyObject *
987
function___annotations___get_impl(PyFunctionObject *self)
988
/*[clinic end generated code: output=a4cf4c884c934cbb input=92643d7186c1ad0c]*/
989
574
{
990
574
    PyObject *d = NULL;
991
574
    if (self->func_annotations == NULL &&
992
528
        (self->func_annotate == NULL || !PyCallable_Check(self->func_annotate))) {
993
280
        PyObject *ann_dict = PyDict_New();
994
280
        if (ann_dict == NULL)
995
0
            return NULL;
996
280
        FT_ATOMIC_STORE_PTR_RELEASE(self->func_annotations, ann_dict);
997
280
    }
998
574
    d = func_get_annotation_dict(self);
999
574
    return Py_XNewRef(d);
1000
574
}
1001
1002
/*[clinic input]
1003
@critical_section
1004
@setter
1005
@deleter
1006
function.__annotations__
1007
[clinic start generated code]*/
1008
1009
static int
1010
function___annotations___set_impl(PyFunctionObject *self, PyObject *value)
1011
/*[clinic end generated code: output=a61795d4a95eede4 input=71f6a58c00ac6745]*/
1012
262
{
1013
262
    if (value == Py_None)
1014
0
        value = NULL;
1015
    /* Legal to del f.func_annotations.
1016
     * Can only set func_annotations to NULL (through C api)
1017
     * or a dict. */
1018
262
    if (value != NULL && !PyDict_Check(value)) {
1019
0
        PyErr_SetString(PyExc_TypeError,
1020
0
            "__annotations__ must be set to a dict object");
1021
0
        return -1;
1022
0
    }
1023
262
    func_set_annotations_and_annotate(self, Py_XNewRef(value), NULL);
1024
262
    return 0;
1025
262
}
1026
1027
/*[clinic input]
1028
@critical_section
1029
@getter
1030
function.__type_params__
1031
1032
Get the declared type parameters for a function.
1033
[clinic start generated code]*/
1034
1035
static PyObject *
1036
function___type_params___get_impl(PyFunctionObject *self)
1037
/*[clinic end generated code: output=eb844d7ffca517a8 input=0864721484293724]*/
1038
949
{
1039
949
    if (self->func_typeparams == NULL) {
1040
873
        return PyTuple_New(0);
1041
873
    }
1042
1043
949
    assert(PyTuple_Check(self->func_typeparams));
1044
76
    return Py_NewRef(self->func_typeparams);
1045
949
}
1046
1047
/*[clinic input]
1048
@critical_section
1049
@setter
1050
function.__type_params__
1051
    value: object(subclass_of='&PyTuple_Type')
1052
[clinic start generated code]*/
1053
1054
static int
1055
function___type_params___set_impl(PyFunctionObject *self, PyObject *value)
1056
/*[clinic end generated code: output=038b4cda220e56fb input=e848b79ec6fec497]*/
1057
669
{
1058
669
    Py_XSETREF(self->func_typeparams, Py_NewRef(value));
1059
669
    return 0;
1060
669
}
1061
1062
PyObject *
1063
_Py_set_function_type_params(PyThreadState *Py_UNUSED(ignored), PyObject *func,
1064
                             PyObject *type_params)
1065
24
{
1066
24
    assert(PyFunction_Check(func));
1067
24
    assert(PyTuple_Check(type_params));
1068
24
    PyFunctionObject *f = (PyFunctionObject *)func;
1069
24
    Py_XSETREF(f->func_typeparams, Py_NewRef(type_params));
1070
24
    return Py_NewRef(func);
1071
24
}
1072
1073
static PyGetSetDef func_getsetlist[] = {
1074
    {"__code__", func_get_code, func_set_code},
1075
    {"__defaults__", func_get_defaults, func_set_defaults},
1076
    {"__kwdefaults__", func_get_kwdefaults, func_set_kwdefaults},
1077
    FUNCTION___ANNOTATIONS___GETSETDEF
1078
    FUNCTION___ANNOTATE___GETSETDEF
1079
    {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
1080
    {"__doc__", func_get_doc, func_set_doc},
1081
    {"__module__", func_get_module, func_set_module},
1082
    {"__name__", func_get_name, func_set_name},
1083
    {"__qualname__", func_get_qualname, func_set_qualname},
1084
    FUNCTION___TYPE_PARAMS___GETSETDEF
1085
    {NULL} /* Sentinel */
1086
};
1087
1088
/* function.__new__() maintains the following invariants for closures.
1089
   The closure must correspond to the free variables of the code object.
1090
1091
   if len(code.co_freevars) == 0:
1092
       closure = NULL
1093
   else:
1094
       len(closure) == len(code.co_freevars)
1095
   for every elt in closure, type(elt) == cell
1096
*/
1097
1098
/*[clinic input]
1099
@vectorcall
1100
@classmethod
1101
function.__new__ as func_new
1102
    code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1103
        a code object
1104
    globals: object(subclass_of="&PyDict_Type")
1105
        the globals dictionary
1106
    name: object = None
1107
        a string that overrides the name from the code object
1108
    argdefs as defaults: object = None
1109
        a tuple that specifies the default argument values
1110
    closure: object = None
1111
        a tuple that supplies the bindings for free variables
1112
    kwdefaults: object = None
1113
        a dictionary that specifies the default keyword argument values
1114
1115
Create a function object.
1116
[clinic start generated code]*/
1117
1118
static PyObject *
1119
func_new_impl(PyTypeObject *type, PyCodeObject *code, PyObject *globals,
1120
              PyObject *name, PyObject *defaults, PyObject *closure,
1121
              PyObject *kwdefaults)
1122
/*[clinic end generated code: output=de72f4c22ac57144 input=264767a5dc845c90]*/
1123
36
{
1124
36
    PyFunctionObject *newfunc;
1125
36
    Py_ssize_t nclosure;
1126
1127
36
    if (name != Py_None && !PyUnicode_Check(name)) {
1128
0
        PyErr_SetString(PyExc_TypeError,
1129
0
                        "arg 3 (name) must be None or string");
1130
0
        return NULL;
1131
0
    }
1132
36
    if (defaults != Py_None && !PyTuple_Check(defaults)) {
1133
0
        PyErr_SetString(PyExc_TypeError,
1134
0
                        "arg 4 (defaults) must be None or tuple");
1135
0
        return NULL;
1136
0
    }
1137
36
    if (!PyTuple_Check(closure)) {
1138
0
        if (code->co_nfreevars && closure == Py_None) {
1139
0
            PyErr_SetString(PyExc_TypeError,
1140
0
                            "arg 5 (closure) must be tuple");
1141
0
            return NULL;
1142
0
        }
1143
0
        else if (closure != Py_None) {
1144
0
            PyErr_SetString(PyExc_TypeError,
1145
0
                "arg 5 (closure) must be None or tuple");
1146
0
            return NULL;
1147
0
        }
1148
0
    }
1149
36
    if (kwdefaults != Py_None && !PyDict_Check(kwdefaults)) {
1150
0
        PyErr_SetString(PyExc_TypeError,
1151
0
                        "arg 6 (kwdefaults) must be None or dict");
1152
0
        return NULL;
1153
0
    }
1154
1155
    /* check that the closure is well-formed */
1156
36
    nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
1157
36
    if (code->co_nfreevars != nclosure)
1158
0
        return PyErr_Format(PyExc_ValueError,
1159
0
                            "%U requires closure of length %d, not %zd",
1160
0
                            code->co_name, code->co_nfreevars, nclosure);
1161
36
    if (nclosure) {
1162
36
        Py_ssize_t i;
1163
72
        for (i = 0; i < nclosure; i++) {
1164
36
            PyObject *o = PyTuple_GET_ITEM(closure, i);
1165
36
            if (!PyCell_Check(o)) {
1166
0
                return PyErr_Format(PyExc_TypeError,
1167
0
                    "arg 5 (closure) expected cell, found %s",
1168
0
                                    Py_TYPE(o)->tp_name);
1169
0
            }
1170
36
        }
1171
36
    }
1172
36
    if (PySys_Audit("function.__new__", "O", code) < 0) {
1173
0
        return NULL;
1174
0
    }
1175
1176
36
    newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
1177
36
                                                 globals);
1178
36
    if (newfunc == NULL) {
1179
0
        return NULL;
1180
0
    }
1181
36
    if (name != Py_None) {
1182
0
        Py_SETREF(newfunc->func_name, Py_NewRef(name));
1183
0
    }
1184
36
    if (defaults != Py_None) {
1185
0
        newfunc->func_defaults = Py_NewRef(defaults);
1186
0
    }
1187
36
    if (closure != Py_None) {
1188
36
        newfunc->func_closure = Py_NewRef(closure);
1189
36
    }
1190
36
    if (kwdefaults != Py_None) {
1191
0
        newfunc->func_kwdefaults = Py_NewRef(kwdefaults);
1192
0
    }
1193
1194
36
    return (PyObject *)newfunc;
1195
36
}
1196
1197
static int
1198
func_clear(PyObject *self)
1199
15.4M
{
1200
15.4M
    PyFunctionObject *op = _PyFunction_CAST(self);
1201
15.4M
    func_clear_version(_PyInterpreterState_GET(), op);
1202
15.4M
    PyObject *globals = op->func_globals;
1203
15.4M
    op->func_globals = NULL;
1204
15.4M
    if (globals != NULL) {
1205
15.4M
        _Py_DECREF_DICT(globals);
1206
15.4M
    }
1207
15.4M
    PyObject *builtins = op->func_builtins;
1208
15.4M
    op->func_builtins = NULL;
1209
15.4M
    if (builtins != NULL) {
1210
15.4M
        _Py_DECREF_BUILTINS(builtins);
1211
15.4M
    }
1212
15.4M
    Py_CLEAR(op->func_module);
1213
15.4M
    Py_CLEAR(op->func_defaults);
1214
15.4M
    Py_CLEAR(op->func_kwdefaults);
1215
15.4M
    Py_CLEAR(op->func_doc);
1216
15.4M
    Py_CLEAR(op->func_dict);
1217
15.4M
    Py_CLEAR(op->func_closure);
1218
15.4M
    Py_CLEAR(op->func_annotations);
1219
15.4M
    Py_CLEAR(op->func_annotate);
1220
15.4M
    Py_CLEAR(op->func_typeparams);
1221
    // Don't Py_CLEAR(op->func_code), since code is always required
1222
    // to be non-NULL. Similarly, name and qualname shouldn't be NULL.
1223
    // However, name and qualname could be str subclasses, so they
1224
    // could have reference cycles. The solution is to replace them
1225
    // with a genuinely immutable string.
1226
15.4M
    Py_SETREF(op->func_name, &_Py_STR(empty));
1227
15.4M
    Py_SETREF(op->func_qualname, &_Py_STR(empty));
1228
15.4M
    return 0;
1229
15.4M
}
1230
1231
static void
1232
func_dealloc(PyObject *self)
1233
15.4M
{
1234
15.4M
    PyFunctionObject *op = _PyFunction_CAST(self);
1235
15.4M
    _PyObject_ResurrectStart(self);
1236
15.4M
    handle_func_event(PyFunction_EVENT_DESTROY, op, NULL);
1237
15.4M
    if (_PyObject_ResurrectEnd(self)) {
1238
0
        return;
1239
0
    }
1240
15.4M
    _PyObject_GC_UNTRACK(op);
1241
15.4M
    FT_CLEAR_WEAKREFS(self, op->func_weakreflist);
1242
15.4M
    (void)func_clear((PyObject*)op);
1243
    // These aren't cleared by func_clear().
1244
15.4M
    _Py_DECREF_CODE((PyCodeObject *)op->func_code);
1245
15.4M
    Py_DECREF(op->func_name);
1246
15.4M
    Py_DECREF(op->func_qualname);
1247
15.4M
    PyObject_GC_Del(op);
1248
15.4M
}
1249
1250
static PyObject*
1251
func_repr(PyObject *self)
1252
0
{
1253
0
    PyFunctionObject *op = _PyFunction_CAST(self);
1254
0
    PyObject *qualname = FT_ATOMIC_LOAD_PTR_ACQUIRE(op->func_qualname);
1255
0
    return PyUnicode_FromFormat("<function %U at %p>", qualname, op);
1256
0
}
1257
1258
static int
1259
func_traverse(PyObject *self, visitproc visit, void *arg)
1260
5.26M
{
1261
5.26M
    PyFunctionObject *f = _PyFunction_CAST(self);
1262
5.26M
    Py_VISIT(f->func_code);
1263
5.26M
    Py_VISIT(f->func_globals);
1264
5.26M
    Py_VISIT(f->func_builtins);
1265
5.26M
    Py_VISIT(f->func_module);
1266
5.26M
    Py_VISIT(f->func_defaults);
1267
5.26M
    Py_VISIT(f->func_kwdefaults);
1268
5.26M
    Py_VISIT(f->func_doc);
1269
5.26M
    Py_VISIT(f->func_name);
1270
5.26M
    Py_VISIT(f->func_dict);
1271
5.26M
    Py_VISIT(f->func_closure);
1272
5.26M
    Py_VISIT(f->func_annotations);
1273
5.26M
    Py_VISIT(f->func_annotate);
1274
5.26M
    Py_VISIT(f->func_typeparams);
1275
5.26M
    Py_VISIT(f->func_qualname);
1276
5.26M
    return 0;
1277
5.26M
}
1278
1279
/* Bind a function to an object */
1280
static PyObject *
1281
func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
1282
31.8M
{
1283
31.8M
    if (obj == Py_None || obj == NULL) {
1284
6.08k
        return Py_NewRef(func);
1285
6.08k
    }
1286
31.8M
    return PyMethod_New(func, obj);
1287
31.8M
}
1288
1289
PyTypeObject PyFunction_Type = {
1290
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1291
    "function",
1292
    sizeof(PyFunctionObject),
1293
    0,
1294
    func_dealloc,                               /* tp_dealloc */
1295
    offsetof(PyFunctionObject, vectorcall),     /* tp_vectorcall_offset */
1296
    0,                                          /* tp_getattr */
1297
    0,                                          /* tp_setattr */
1298
    0,                                          /* tp_as_async */
1299
    func_repr,                                  /* tp_repr */
1300
    0,                                          /* tp_as_number */
1301
    0,                                          /* tp_as_sequence */
1302
    0,                                          /* tp_as_mapping */
1303
    0,                                          /* tp_hash */
1304
    PyVectorcall_Call,                          /* tp_call */
1305
    0,                                          /* tp_str */
1306
    0,                                          /* tp_getattro */
1307
    0,                                          /* tp_setattro */
1308
    0,                                          /* tp_as_buffer */
1309
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1310
    Py_TPFLAGS_HAVE_VECTORCALL |
1311
    Py_TPFLAGS_METHOD_DESCRIPTOR,               /* tp_flags */
1312
    func_new__doc__,                            /* tp_doc */
1313
    func_traverse,                              /* tp_traverse */
1314
    func_clear,                                 /* tp_clear */
1315
    0,                                          /* tp_richcompare */
1316
    offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
1317
    0,                                          /* tp_iter */
1318
    0,                                          /* tp_iternext */
1319
    0,                                          /* tp_methods */
1320
    func_memberlist,                            /* tp_members */
1321
    func_getsetlist,                            /* tp_getset */
1322
    0,                                          /* tp_base */
1323
    0,                                          /* tp_dict */
1324
    func_descr_get,                             /* tp_descr_get */
1325
    0,                                          /* tp_descr_set */
1326
    offsetof(PyFunctionObject, func_dict),      /* tp_dictoffset */
1327
    0,                                          /* tp_init */
1328
    0,                                          /* tp_alloc */
1329
    func_new,                                   /* tp_new */
1330
    .tp_vectorcall = func_vectorcall,
1331
};
1332
1333
1334
int
1335
_PyFunction_VerifyStateless(PyThreadState *tstate, PyObject *func)
1336
0
{
1337
0
    assert(!PyErr_Occurred());
1338
0
    assert(PyFunction_Check(func));
1339
1340
    // Check the globals.
1341
0
    PyObject *globalsns = PyFunction_GET_GLOBALS(func);
1342
0
    if (globalsns != NULL && !PyDict_Check(globalsns)) {
1343
0
        _PyErr_Format(tstate, PyExc_TypeError,
1344
0
                      "unsupported globals %R", globalsns);
1345
0
        return -1;
1346
0
    }
1347
    // Check the builtins.
1348
0
    PyObject *builtinsns = _PyFunction_GET_BUILTINS(func);
1349
0
    if (builtinsns != NULL && !PyDict_Check(builtinsns)) {
1350
0
        _PyErr_Format(tstate, PyExc_TypeError,
1351
0
                      "unsupported builtins %R", builtinsns);
1352
0
        return -1;
1353
0
    }
1354
    // Disallow __defaults__.
1355
0
    PyObject *defaults = PyFunction_GET_DEFAULTS(func);
1356
0
    if (defaults != NULL) {
1357
0
        assert(PyTuple_Check(defaults));  // per PyFunction_New()
1358
0
        if (PyTuple_GET_SIZE(defaults) > 0) {
1359
0
            _PyErr_SetString(tstate, PyExc_ValueError,
1360
0
                             "defaults not supported");
1361
0
            return -1;
1362
0
        }
1363
0
    }
1364
    // Disallow __kwdefaults__.
1365
0
    PyObject *kwdefaults = PyFunction_GET_KW_DEFAULTS(func);
1366
0
    if (kwdefaults != NULL) {
1367
0
        assert(PyDict_Check(kwdefaults));  // per PyFunction_New()
1368
0
        if (PyDict_Size(kwdefaults) > 0) {
1369
0
            _PyErr_SetString(tstate, PyExc_ValueError,
1370
0
                             "keyword defaults not supported");
1371
0
            return -1;
1372
0
        }
1373
0
    }
1374
    // Disallow __closure__.
1375
0
    PyObject *closure = PyFunction_GET_CLOSURE(func);
1376
0
    if (closure != NULL) {
1377
0
        assert(PyTuple_Check(closure));  // per PyFunction_New()
1378
0
        if (PyTuple_GET_SIZE(closure) > 0) {
1379
0
            _PyErr_SetString(tstate, PyExc_ValueError, "closures not supported");
1380
0
            return -1;
1381
0
        }
1382
0
    }
1383
    // Check the code.
1384
0
    PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
1385
0
    if (_PyCode_VerifyStateless(tstate, co, NULL, globalsns, builtinsns) < 0) {
1386
0
        return -1;
1387
0
    }
1388
0
    return 0;
1389
0
}
1390
1391
1392
static int
1393
functools_copy_attr(PyObject *wrapper, PyObject *wrapped, PyObject *name)
1394
18.8k
{
1395
18.8k
    PyObject *value;
1396
18.8k
    int res = PyObject_GetOptionalAttr(wrapped, name, &value);
1397
18.8k
    if (value != NULL) {
1398
18.8k
        res = PyObject_SetAttr(wrapper, name, value);
1399
18.8k
        Py_DECREF(value);
1400
18.8k
    }
1401
18.8k
    return res;
1402
18.8k
}
1403
1404
// Similar to functools.wraps(wrapper, wrapped)
1405
static int
1406
functools_wraps(PyObject *wrapper, PyObject *wrapped)
1407
4.71k
{
1408
4.71k
#define COPY_ATTR(ATTR) \
1409
18.8k
    do { \
1410
18.8k
        if (functools_copy_attr(wrapper, wrapped, &_Py_ID(ATTR)) < 0) { \
1411
0
            return -1; \
1412
0
        } \
1413
18.8k
    } while (0) \
1414
4.71k
1415
4.71k
    COPY_ATTR(__module__);
1416
4.71k
    COPY_ATTR(__name__);
1417
4.71k
    COPY_ATTR(__qualname__);
1418
4.71k
    COPY_ATTR(__doc__);
1419
4.71k
    return 0;
1420
1421
4.71k
#undef COPY_ATTR
1422
4.71k
}
1423
1424
// Used for wrapping __annotations__ and __annotate__ on classmethod
1425
// and staticmethod objects.
1426
static PyObject *
1427
descriptor_get_wrapped_attribute(PyObject *wrapped, PyObject *obj, PyObject *name)
1428
0
{
1429
0
    PyObject *dict = PyObject_GenericGetDict(obj, NULL);
1430
0
    if (dict == NULL) {
1431
0
        return NULL;
1432
0
    }
1433
0
    PyObject *res;
1434
0
    if (PyDict_GetItemRef(dict, name, &res) < 0) {
1435
0
        Py_DECREF(dict);
1436
0
        return NULL;
1437
0
    }
1438
0
    if (res != NULL) {
1439
0
        Py_DECREF(dict);
1440
0
        return res;
1441
0
    }
1442
0
    res = PyObject_GetAttr(wrapped, name);
1443
0
    if (res == NULL) {
1444
0
        Py_DECREF(dict);
1445
0
        return NULL;
1446
0
    }
1447
0
    if (PyDict_SetItem(dict, name, res) < 0) {
1448
0
        Py_DECREF(dict);
1449
0
        Py_DECREF(res);
1450
0
        return NULL;
1451
0
    }
1452
0
    Py_DECREF(dict);
1453
0
    return res;
1454
0
}
1455
1456
static int
1457
descriptor_set_wrapped_attribute(PyObject *oobj, PyObject *name, PyObject *value,
1458
                                 char *type_name)
1459
0
{
1460
0
    PyObject *dict = PyObject_GenericGetDict(oobj, NULL);
1461
0
    if (dict == NULL) {
1462
0
        return -1;
1463
0
    }
1464
0
    if (value == NULL) {
1465
0
        if (PyDict_DelItem(dict, name) < 0) {
1466
0
            if (PyErr_ExceptionMatches(PyExc_KeyError)) {
1467
0
                PyErr_Clear();
1468
0
                PyErr_Format(PyExc_AttributeError,
1469
0
                             "'%.200s' object has no attribute '%U'",
1470
0
                             type_name, name);
1471
0
                Py_DECREF(dict);
1472
0
                return -1;
1473
0
            }
1474
0
            else {
1475
0
                Py_DECREF(dict);
1476
0
                return -1;
1477
0
            }
1478
0
        }
1479
0
        Py_DECREF(dict);
1480
0
        return 0;
1481
0
    }
1482
0
    else {
1483
0
        int result = PyDict_SetItem(dict, name, value);
1484
0
        Py_DECREF(dict);
1485
0
        return result;
1486
0
    }
1487
0
}
1488
1489
1490
/* Class method object */
1491
1492
/* A class method receives the class as implicit first argument,
1493
   just like an instance method receives the instance.
1494
   To declare a class method, use this idiom:
1495
1496
     class C:
1497
         @classmethod
1498
         def f(cls, arg1, arg2, argN):
1499
             ...
1500
1501
   It can be called either on the class (e.g. C.f()) or on an instance
1502
   (e.g. C().f()); the instance is ignored except for its class.
1503
   If a class method is called for a derived class, the derived class
1504
   object is passed as the implied first argument.
1505
1506
   Class methods are different than C++ or Java static methods.
1507
   If you want those, see static methods below.
1508
*/
1509
1510
typedef struct {
1511
    PyObject_HEAD
1512
    PyObject *cm_callable;
1513
    PyObject *cm_dict;
1514
} classmethod;
1515
1516
#define _PyClassMethod_CAST(cm) \
1517
513k
    (assert(PyObject_TypeCheck((cm), &PyClassMethod_Type)), \
1518
513k
     _Py_CAST(classmethod*, cm))
1519
1520
static void
1521
cm_dealloc(PyObject *self)
1522
50
{
1523
50
    classmethod *cm = _PyClassMethod_CAST(self);
1524
50
    _PyObject_GC_UNTRACK((PyObject *)cm);
1525
50
    Py_XDECREF(cm->cm_callable);
1526
50
    Py_XDECREF(cm->cm_dict);
1527
50
    Py_TYPE(cm)->tp_free((PyObject *)cm);
1528
50
}
1529
1530
static int
1531
cm_traverse(PyObject *self, visitproc visit, void *arg)
1532
150k
{
1533
150k
    classmethod *cm = _PyClassMethod_CAST(self);
1534
150k
    Py_VISIT(cm->cm_callable);
1535
150k
    Py_VISIT(cm->cm_dict);
1536
150k
    return 0;
1537
150k
}
1538
1539
static int
1540
cm_clear(PyObject *self)
1541
50
{
1542
50
    classmethod *cm = _PyClassMethod_CAST(self);
1543
50
    Py_CLEAR(cm->cm_callable);
1544
50
    Py_CLEAR(cm->cm_dict);
1545
50
    return 0;
1546
50
}
1547
1548
1549
static PyObject *
1550
cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
1551
16.3M
{
1552
16.3M
    classmethod *cm = (classmethod *)self;
1553
16.3M
    if (type == NULL)
1554
0
        type = (PyObject *)(Py_TYPE(obj));
1555
16.3M
    return PyMethod_New(cm->cm_callable, type);
1556
16.3M
}
1557
1558
static int
1559
cm_set_callable(classmethod *cm, PyObject *callable)
1560
6.10k
{
1561
6.10k
    assert(callable != NULL);
1562
6.10k
    if (cm->cm_callable == callable) {
1563
        // cm_init() sets the same callable than cm_new()
1564
3.01k
        return 0;
1565
3.01k
    }
1566
1567
3.09k
    Py_XSETREF(cm->cm_callable, Py_NewRef(callable));
1568
3.09k
    return functools_wraps((PyObject *)cm, cm->cm_callable);
1569
6.10k
}
1570
1571
static PyObject *
1572
cm_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1573
3.01k
{
1574
3.01k
    if (!_PyArg_NoKeywords("classmethod", kwds)) {
1575
0
        return NULL;
1576
0
    }
1577
3.01k
    PyObject *callable;  // borrowed ref
1578
3.01k
    if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable)) {
1579
0
        return NULL;
1580
0
    }
1581
1582
3.01k
    classmethod *cm = (classmethod *)PyType_GenericAlloc(type, 0);
1583
3.01k
    if (cm == NULL) {
1584
0
        return NULL;
1585
0
    }
1586
3.01k
    _PyObject_SetDeferredRefcount((PyObject *)cm);
1587
3.01k
    if (cm_set_callable(cm, callable) < 0) {
1588
0
        Py_DECREF(cm);
1589
0
        return NULL;
1590
0
    }
1591
3.01k
    return (PyObject *)cm;
1592
3.01k
}
1593
1594
static int
1595
cm_init(PyObject *self, PyObject *args, PyObject *kwds)
1596
3.01k
{
1597
3.01k
    if (!_PyArg_NoKeywords("classmethod", kwds)) {
1598
0
        return -1;
1599
0
    }
1600
3.01k
    PyObject *callable;  // borrowed ref
1601
3.01k
    if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable)) {
1602
0
        return -1;
1603
0
    }
1604
1605
3.01k
    classmethod *cm = (classmethod *)self;
1606
3.01k
    return cm_set_callable(cm, callable);
1607
3.01k
}
1608
1609
static PyMemberDef cm_memberlist[] = {
1610
    {"__func__", _Py_T_OBJECT, offsetof(classmethod, cm_callable), Py_READONLY},
1611
    {"__wrapped__", _Py_T_OBJECT, offsetof(classmethod, cm_callable), Py_READONLY},
1612
    {NULL}  /* Sentinel */
1613
};
1614
1615
static PyObject *
1616
cm_get___isabstractmethod__(PyObject *self, void *closure)
1617
1.31k
{
1618
1.31k
    classmethod *cm = _PyClassMethod_CAST(self);
1619
1.31k
    int res = _PyObject_IsAbstract(cm->cm_callable);
1620
1.31k
    if (res == -1) {
1621
0
        return NULL;
1622
0
    }
1623
1.31k
    else if (res) {
1624
0
        Py_RETURN_TRUE;
1625
0
    }
1626
1.31k
    Py_RETURN_FALSE;
1627
1.31k
}
1628
1629
static PyObject *
1630
cm_get___annotations__(PyObject *self, void *closure)
1631
0
{
1632
0
    classmethod *cm = _PyClassMethod_CAST(self);
1633
0
    return descriptor_get_wrapped_attribute(cm->cm_callable, self, &_Py_ID(__annotations__));
1634
0
}
1635
1636
static int
1637
cm_set___annotations__(PyObject *self, PyObject *value, void *closure)
1638
0
{
1639
0
    return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotations__), value, "classmethod");
1640
0
}
1641
1642
static PyObject *
1643
cm_get___annotate__(PyObject *self, void *closure)
1644
0
{
1645
0
    classmethod *cm = _PyClassMethod_CAST(self);
1646
0
    return descriptor_get_wrapped_attribute(cm->cm_callable, self, &_Py_ID(__annotate__));
1647
0
}
1648
1649
static int
1650
cm_set___annotate__(PyObject *self, PyObject *value, void *closure)
1651
0
{
1652
0
    return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotate__), value, "classmethod");
1653
0
}
1654
1655
1656
static PyGetSetDef cm_getsetlist[] = {
1657
    {"__isabstractmethod__", cm_get___isabstractmethod__, NULL, NULL, NULL},
1658
    {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
1659
    {"__annotations__", cm_get___annotations__, cm_set___annotations__, NULL, NULL},
1660
    {"__annotate__", cm_get___annotate__, cm_set___annotate__, NULL, NULL},
1661
    {NULL} /* Sentinel */
1662
};
1663
1664
static PyMethodDef cm_methodlist[] = {
1665
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, NULL},
1666
    {NULL} /* Sentinel */
1667
};
1668
1669
static PyObject*
1670
cm_repr(PyObject *self)
1671
0
{
1672
0
    classmethod *cm = _PyClassMethod_CAST(self);
1673
0
    return PyUnicode_FromFormat("<classmethod(%R)>", cm->cm_callable);
1674
0
}
1675
1676
PyDoc_STRVAR(classmethod_doc,
1677
"classmethod(function, /)\n\
1678
--\n\
1679
\n\
1680
Convert a function to be a class method.\n\
1681
\n\
1682
A class method receives the class as implicit first argument,\n\
1683
just like an instance method receives the instance.\n\
1684
To declare a class method, use this idiom:\n\
1685
\n\
1686
  class C:\n\
1687
      @classmethod\n\
1688
      def f(cls, arg1, arg2, argN):\n\
1689
          ...\n\
1690
\n\
1691
It can be called either on the class (e.g. C.f()) or on an instance\n\
1692
(e.g. C().f()).  The instance is ignored except for its class.\n\
1693
If a class method is called for a derived class, the derived class\n\
1694
object is passed as the implied first argument.\n\
1695
\n\
1696
Class methods are different than C++ or Java static methods.\n\
1697
If you want those, see the staticmethod builtin.");
1698
1699
PyTypeObject PyClassMethod_Type = {
1700
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1701
    "classmethod",
1702
    sizeof(classmethod),
1703
    0,
1704
    cm_dealloc,                                 /* tp_dealloc */
1705
    0,                                          /* tp_vectorcall_offset */
1706
    0,                                          /* tp_getattr */
1707
    0,                                          /* tp_setattr */
1708
    0,                                          /* tp_as_async */
1709
    cm_repr,                                    /* tp_repr */
1710
    0,                                          /* tp_as_number */
1711
    0,                                          /* tp_as_sequence */
1712
    0,                                          /* tp_as_mapping */
1713
    0,                                          /* tp_hash */
1714
    0,                                          /* tp_call */
1715
    0,                                          /* tp_str */
1716
    0,                                          /* tp_getattro */
1717
    0,                                          /* tp_setattro */
1718
    0,                                          /* tp_as_buffer */
1719
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1720
    classmethod_doc,                            /* tp_doc */
1721
    cm_traverse,                                /* tp_traverse */
1722
    cm_clear,                                   /* tp_clear */
1723
    0,                                          /* tp_richcompare */
1724
    0,                                          /* tp_weaklistoffset */
1725
    0,                                          /* tp_iter */
1726
    0,                                          /* tp_iternext */
1727
    cm_methodlist,                              /* tp_methods */
1728
    cm_memberlist,                              /* tp_members */
1729
    cm_getsetlist,                              /* tp_getset */
1730
    0,                                          /* tp_base */
1731
    0,                                          /* tp_dict */
1732
    cm_descr_get,                               /* tp_descr_get */
1733
    0,                                          /* tp_descr_set */
1734
    offsetof(classmethod, cm_dict),             /* tp_dictoffset */
1735
    cm_init,                                    /* tp_init */
1736
    PyType_GenericAlloc,                        /* tp_alloc */
1737
    cm_new,                                     /* tp_new */
1738
    PyObject_GC_Del,                            /* tp_free */
1739
};
1740
1741
PyObject *
1742
PyClassMethod_New(PyObject *callable)
1743
78
{
1744
78
    classmethod *cm = (classmethod *)
1745
78
        PyType_GenericAlloc(&PyClassMethod_Type, 0);
1746
78
    if (cm == NULL) {
1747
0
        return NULL;
1748
0
    }
1749
78
    if (cm_set_callable(cm, callable) < 0) {
1750
0
        Py_DECREF(cm);
1751
0
        return NULL;
1752
0
    }
1753
78
    return (PyObject *)cm;
1754
78
}
1755
1756
1757
/* Static method object */
1758
1759
/* A static method does not receive an implicit first argument.
1760
   To declare a static method, use this idiom:
1761
1762
     class C:
1763
         @staticmethod
1764
         def f(arg1, arg2, argN):
1765
             ...
1766
1767
   It can be called either on the class (e.g. C.f()) or on an instance
1768
   (e.g. C().f()). Both the class and the instance are ignored, and
1769
   neither is passed implicitly as the first argument to the method.
1770
1771
   Static methods in Python are similar to those found in Java or C++.
1772
   For a more advanced concept, see class methods above.
1773
*/
1774
1775
typedef struct {
1776
    PyObject_HEAD
1777
    PyObject *sm_callable;
1778
    PyObject *sm_dict;
1779
} staticmethod;
1780
1781
#define _PyStaticMethod_CAST(cm) \
1782
23.7M
    (assert(PyObject_TypeCheck((cm), &PyStaticMethod_Type)), \
1783
23.7M
     _Py_CAST(staticmethod*, cm))
1784
1785
static void
1786
sm_dealloc(PyObject *self)
1787
88
{
1788
88
    staticmethod *sm = _PyStaticMethod_CAST(self);
1789
88
    _PyObject_GC_UNTRACK((PyObject *)sm);
1790
88
    Py_XDECREF(sm->sm_callable);
1791
88
    Py_XDECREF(sm->sm_dict);
1792
88
    Py_TYPE(sm)->tp_free((PyObject *)sm);
1793
88
}
1794
1795
static int
1796
sm_traverse(PyObject *self, visitproc visit, void *arg)
1797
71.0k
{
1798
71.0k
    staticmethod *sm = _PyStaticMethod_CAST(self);
1799
71.0k
    Py_VISIT(sm->sm_callable);
1800
71.0k
    Py_VISIT(sm->sm_dict);
1801
71.0k
    return 0;
1802
71.0k
}
1803
1804
static int
1805
sm_clear(PyObject *self)
1806
0
{
1807
0
    staticmethod *sm = _PyStaticMethod_CAST(self);
1808
0
    Py_CLEAR(sm->sm_callable);
1809
0
    Py_CLEAR(sm->sm_dict);
1810
0
    return 0;
1811
0
}
1812
1813
static PyObject *
1814
sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
1815
7.20k
{
1816
7.20k
    staticmethod *sm = (staticmethod *)self;
1817
7.20k
    return Py_NewRef(sm->sm_callable);
1818
7.20k
}
1819
1820
static int
1821
sm_set_callable(staticmethod *sm, PyObject *callable)
1822
2.41k
{
1823
2.41k
    assert(callable != NULL);
1824
2.41k
    if (sm->sm_callable == callable) {
1825
        // sm_init() sets the same callable than sm_new()
1826
793
        return 0;
1827
793
    }
1828
1829
1.62k
    Py_XSETREF(sm->sm_callable, Py_NewRef(callable));
1830
1.62k
    return functools_wraps((PyObject *)sm, sm->sm_callable);
1831
2.41k
}
1832
1833
static PyObject *
1834
sm_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1835
793
{
1836
793
    if (!_PyArg_NoKeywords("staticmethod", kwds)) {
1837
0
        return NULL;
1838
0
    }
1839
793
    PyObject *callable;  // borrowed ref
1840
793
    if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable)) {
1841
0
        return NULL;
1842
0
    }
1843
1844
793
    staticmethod *sm = (staticmethod *)PyType_GenericAlloc(type, 0);
1845
793
    if (sm == NULL) {
1846
0
        return NULL;
1847
0
    }
1848
793
    _PyObject_SetDeferredRefcount((PyObject *)sm);
1849
793
    if (sm_set_callable(sm, callable) < 0) {
1850
0
        Py_DECREF(sm);
1851
0
        return NULL;
1852
0
    }
1853
793
    return (PyObject *)sm;
1854
793
}
1855
1856
static int
1857
sm_init(PyObject *self, PyObject *args, PyObject *kwds)
1858
793
{
1859
793
    if (!_PyArg_NoKeywords("staticmethod", kwds)) {
1860
0
        return -1;
1861
0
    }
1862
793
    PyObject *callable;  // borrowed ref
1863
793
    if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable)) {
1864
0
        return -1;
1865
0
    }
1866
1867
793
    staticmethod *sm = (staticmethod *)self;
1868
793
    return sm_set_callable(sm, callable);
1869
793
}
1870
1871
static PyObject*
1872
sm_call(PyObject *callable, PyObject *args, PyObject *kwargs)
1873
0
{
1874
0
    staticmethod *sm = (staticmethod *)callable;
1875
0
    return PyObject_Call(sm->sm_callable, args, kwargs);
1876
0
}
1877
1878
static PyMemberDef sm_memberlist[] = {
1879
    {"__func__", _Py_T_OBJECT, offsetof(staticmethod, sm_callable), Py_READONLY},
1880
    {"__wrapped__", _Py_T_OBJECT, offsetof(staticmethod, sm_callable), Py_READONLY},
1881
    {NULL}  /* Sentinel */
1882
};
1883
1884
static PyObject *
1885
sm_get___isabstractmethod__(PyObject *self, void *closure)
1886
71
{
1887
71
    staticmethod *sm = _PyStaticMethod_CAST(self);
1888
71
    int res = _PyObject_IsAbstract(sm->sm_callable);
1889
71
    if (res == -1) {
1890
0
        return NULL;
1891
0
    }
1892
71
    else if (res) {
1893
0
        Py_RETURN_TRUE;
1894
0
    }
1895
71
    Py_RETURN_FALSE;
1896
71
}
1897
1898
static PyObject *
1899
sm_get___annotations__(PyObject *self, void *closure)
1900
0
{
1901
0
    staticmethod *sm = _PyStaticMethod_CAST(self);
1902
0
    return descriptor_get_wrapped_attribute(sm->sm_callable, self, &_Py_ID(__annotations__));
1903
0
}
1904
1905
static int
1906
sm_set___annotations__(PyObject *self, PyObject *value, void *closure)
1907
0
{
1908
0
    return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotations__), value, "staticmethod");
1909
0
}
1910
1911
static PyObject *
1912
sm_get___annotate__(PyObject *self, void *closure)
1913
0
{
1914
0
    staticmethod *sm = _PyStaticMethod_CAST(self);
1915
0
    return descriptor_get_wrapped_attribute(sm->sm_callable, self, &_Py_ID(__annotate__));
1916
0
}
1917
1918
static int
1919
sm_set___annotate__(PyObject *self, PyObject *value, void *closure)
1920
0
{
1921
0
    return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotate__), value, "staticmethod");
1922
0
}
1923
1924
static PyGetSetDef sm_getsetlist[] = {
1925
    {"__isabstractmethod__", sm_get___isabstractmethod__, NULL, NULL, NULL},
1926
    {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
1927
    {"__annotations__", sm_get___annotations__, sm_set___annotations__, NULL, NULL},
1928
    {"__annotate__", sm_get___annotate__, sm_set___annotate__, NULL, NULL},
1929
    {NULL} /* Sentinel */
1930
};
1931
1932
static PyMethodDef sm_methodlist[] = {
1933
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, NULL},
1934
    {NULL} /* Sentinel */
1935
};
1936
1937
static PyObject*
1938
sm_repr(PyObject *self)
1939
0
{
1940
0
    staticmethod *sm = _PyStaticMethod_CAST(self);
1941
0
    return PyUnicode_FromFormat("<staticmethod(%R)>", sm->sm_callable);
1942
0
}
1943
1944
PyDoc_STRVAR(staticmethod_doc,
1945
"staticmethod(function, /)\n\
1946
--\n\
1947
\n\
1948
Convert a function to be a static method.\n\
1949
\n\
1950
A static method does not receive an implicit first argument.\n\
1951
To declare a static method, use this idiom:\n\
1952
\n\
1953
     class C:\n\
1954
         @staticmethod\n\
1955
         def f(arg1, arg2, argN):\n\
1956
             ...\n\
1957
\n\
1958
It can be called either on the class (e.g. C.f()) or on an instance\n\
1959
(e.g. C().f()). Both the class and the instance are ignored, and\n\
1960
neither is passed implicitly as the first argument to the method.\n\
1961
\n\
1962
Static methods in Python are similar to those found in Java or C++.\n\
1963
For a more advanced concept, see the classmethod builtin.");
1964
1965
PyTypeObject PyStaticMethod_Type = {
1966
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1967
    "staticmethod",
1968
    sizeof(staticmethod),
1969
    0,
1970
    sm_dealloc,                                 /* tp_dealloc */
1971
    0,                                          /* tp_vectorcall_offset */
1972
    0,                                          /* tp_getattr */
1973
    0,                                          /* tp_setattr */
1974
    0,                                          /* tp_as_async */
1975
    sm_repr,                                    /* tp_repr */
1976
    0,                                          /* tp_as_number */
1977
    0,                                          /* tp_as_sequence */
1978
    0,                                          /* tp_as_mapping */
1979
    0,                                          /* tp_hash */
1980
    sm_call,                                    /* tp_call */
1981
    0,                                          /* tp_str */
1982
    0,                                          /* tp_getattro */
1983
    0,                                          /* tp_setattro */
1984
    0,                                          /* tp_as_buffer */
1985
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1986
    staticmethod_doc,                           /* tp_doc */
1987
    sm_traverse,                                /* tp_traverse */
1988
    sm_clear,                                   /* tp_clear */
1989
    0,                                          /* tp_richcompare */
1990
    0,                                          /* tp_weaklistoffset */
1991
    0,                                          /* tp_iter */
1992
    0,                                          /* tp_iternext */
1993
    sm_methodlist,                              /* tp_methods */
1994
    sm_memberlist,                              /* tp_members */
1995
    sm_getsetlist,                              /* tp_getset */
1996
    0,                                          /* tp_base */
1997
    0,                                          /* tp_dict */
1998
    sm_descr_get,                               /* tp_descr_get */
1999
    0,                                          /* tp_descr_set */
2000
    offsetof(staticmethod, sm_dict),            /* tp_dictoffset */
2001
    sm_init,                                    /* tp_init */
2002
    PyType_GenericAlloc,                        /* tp_alloc */
2003
    sm_new,                                     /* tp_new */
2004
    PyObject_GC_Del,                            /* tp_free */
2005
};
2006
2007
PyObject *
2008
PyStaticMethod_New(PyObject *callable)
2009
828
{
2010
828
    staticmethod *sm = (staticmethod *)
2011
828
        PyType_GenericAlloc(&PyStaticMethod_Type, 0);
2012
828
    if (sm == NULL) {
2013
0
        return NULL;
2014
0
    }
2015
828
    _PyObject_SetDeferredRefcount((PyObject *)sm);
2016
828
    if (sm_set_callable(sm, callable) < 0) {
2017
0
        Py_DECREF(sm);
2018
0
        return NULL;
2019
0
    }
2020
828
    return (PyObject *)sm;
2021
828
}
2022
2023
PyObject *
2024
_PyClassMethod_GetFunc(PyObject *self)
2025
361k
{
2026
361k
    classmethod *cm = _PyClassMethod_CAST(self);
2027
361k
    return cm->cm_callable;
2028
361k
}
2029
2030
PyObject *
2031
_PyStaticMethod_GetFunc(PyObject *self)
2032
23.6M
{
2033
    staticmethod *sm = _PyStaticMethod_CAST(self);
2034
23.6M
    return sm->sm_callable;
2035
23.6M
}