Coverage Report

Created: 2026-07-14 06:16

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