Coverage Report

Created: 2026-05-16 06:46

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
36.7M
{
56
36.7M
    assert(Py_REFCNT(func) > 0);
57
36.7M
    PyInterpreterState *interp = _PyInterpreterState_GET();
58
36.7M
    assert(interp->_initialized);
59
36.7M
    if (interp->active_func_watchers) {
60
0
        notify_func_watchers(interp, event, func, new_value);
61
0
    }
62
36.7M
    switch (event) {
63
7.51k
        case PyFunction_EVENT_MODIFY_CODE:
64
15.0k
        case PyFunction_EVENT_MODIFY_DEFAULTS:
65
15.2k
        case PyFunction_EVENT_MODIFY_KWDEFAULTS:
66
25.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
25.2k
            RARE_EVENT_INTERP_INC(interp, func_modification);
75
25.2k
            break;
76
36.7M
        default:
77
36.7M
            break;
78
36.7M
    }
79
36.7M
}
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.72k
{
118
7.72k
    PyObject *module;
119
7.72k
    if (PyDict_GetItemRef(constr->fc_globals, &_Py_ID(__name__), &module) < 0) {
120
0
        return NULL;
121
0
    }
122
123
7.72k
    PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
124
7.72k
    if (op == NULL) {
125
0
        Py_XDECREF(module);
126
0
        return NULL;
127
0
    }
128
7.72k
    _Py_INCREF_DICT(constr->fc_globals);
129
7.72k
    op->func_globals = constr->fc_globals;
130
7.72k
    _Py_INCREF_BUILTINS(constr->fc_builtins);
131
7.72k
    op->func_builtins = constr->fc_builtins;
132
7.72k
    op->func_name = Py_NewRef(constr->fc_name);
133
7.72k
    op->func_qualname = Py_NewRef(constr->fc_qualname);
134
7.72k
    _Py_INCREF_CODE((PyCodeObject *)constr->fc_code);
135
7.72k
    op->func_code = constr->fc_code;
136
7.72k
    op->func_defaults = Py_XNewRef(constr->fc_defaults);
137
7.72k
    op->func_kwdefaults = Py_XNewRef(constr->fc_kwdefaults);
138
7.72k
    op->func_closure = Py_XNewRef(constr->fc_closure);
139
7.72k
    op->func_doc = Py_NewRef(Py_None);
140
7.72k
    op->func_dict = NULL;
141
7.72k
    op->func_weakreflist = NULL;
142
7.72k
    op->func_module = module;
143
7.72k
    op->func_annotations = NULL;
144
7.72k
    op->func_annotate = NULL;
145
7.72k
    op->func_typeparams = NULL;
146
7.72k
    op->vectorcall = _PyFunction_Vectorcall;
147
7.72k
    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.72k
    _PyObject_GC_TRACK(op);
152
7.72k
    handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
153
7.72k
    return op;
154
7.72k
}
155
156
PyObject *
157
PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
158
18.3M
{
159
18.3M
    assert(globals != NULL);
160
18.3M
    assert(PyAnyDict_Check(globals));
161
18.3M
    _Py_INCREF_DICT(globals);
162
163
18.3M
    PyCodeObject *code_obj = (PyCodeObject *)code;
164
18.3M
    _Py_INCREF_CODE(code_obj);
165
166
18.3M
    assert(code_obj->co_name != NULL);
167
18.3M
    PyObject *name = Py_NewRef(code_obj->co_name);
168
169
18.3M
    if (!qualname) {
170
18.3M
        qualname = code_obj->co_qualname;
171
18.3M
    }
172
18.3M
    assert(qualname != NULL);
173
18.3M
    Py_INCREF(qualname);
174
175
18.3M
    PyObject *consts = code_obj->co_consts;
176
18.3M
    assert(PyTuple_Check(consts));
177
18.3M
    PyObject *doc;
178
18.3M
    if (code_obj->co_flags & CO_HAS_DOCSTRING) {
179
56.5k
        assert(PyTuple_Size(consts) >= 1);
180
56.5k
        doc = PyTuple_GetItem(consts, 0);
181
56.5k
        if (!PyUnicode_Check(doc)) {
182
0
            doc = Py_None;
183
0
        }
184
56.5k
    }
185
18.3M
    else {
186
18.3M
        doc = Py_None;
187
18.3M
    }
188
18.3M
    Py_INCREF(doc);
189
190
    // __module__: Use globals['__name__'] if it exists, or NULL.
191
18.3M
    PyObject *module;
192
18.3M
    PyObject *builtins = NULL;
193
18.3M
    if (PyDict_GetItemRef(globals, &_Py_ID(__name__), &module) < 0) {
194
0
        goto error;
195
0
    }
196
197
18.3M
    builtins = _PyDict_LoadBuiltinsFromGlobals(globals);
198
18.3M
    if (builtins == NULL) {
199
0
        goto error;
200
0
    }
201
202
18.3M
    PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
203
18.3M
    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
18.3M
    op->func_globals = globals;
210
18.3M
    op->func_builtins = builtins;
211
18.3M
    op->func_name = name;
212
18.3M
    op->func_qualname = qualname;
213
18.3M
    op->func_code = (PyObject*)code_obj;
214
18.3M
    op->func_defaults = NULL;    // No default positional arguments
215
18.3M
    op->func_kwdefaults = NULL;  // No default keyword arguments
216
18.3M
    op->func_closure = NULL;
217
18.3M
    op->func_doc = doc;
218
18.3M
    op->func_dict = NULL;
219
18.3M
    op->func_weakreflist = NULL;
220
18.3M
    op->func_module = module;
221
18.3M
    op->func_annotations = NULL;
222
18.3M
    op->func_annotate = NULL;
223
18.3M
    op->func_typeparams = NULL;
224
18.3M
    op->vectorcall = _PyFunction_Vectorcall;
225
18.3M
    op->func_version = FUNC_VERSION_UNSET;
226
18.3M
    if (((code_obj->co_flags & CO_NESTED) == 0) ||
227
18.2M
        (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
93.4k
        _PyObject_SetDeferredRefcount((PyObject *)op);
235
93.4k
    }
236
18.3M
    _PyObject_GC_TRACK(op);
237
18.3M
    handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
238
18.3M
    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
18.3M
}
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
36.7M
{
313
36.7M
    return interp->func_state.func_version_cache +
314
36.7M
           (version % FUNC_VERSION_CACHE_SIZE);
315
36.7M
}
316
#endif
317
318
void
319
_PyFunction_SetVersion(PyFunctionObject *func, uint32_t version)
320
18.3M
{
321
18.3M
    assert(func->func_version == FUNC_VERSION_UNSET);
322
18.3M
    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
18.3M
    func->func_version = version;
326
18.3M
#ifndef Py_GIL_DISABLED
327
18.3M
    PyInterpreterState *interp = _PyInterpreterState_GET();
328
18.3M
    struct _func_version_cache_item *slot = get_cache_item(interp, version);
329
18.3M
    slot->func = func;
330
18.3M
    slot->code = func->func_code;
331
18.3M
#endif
332
18.3M
}
333
334
static void
335
func_clear_version(PyInterpreterState *interp, PyFunctionObject *func)
336
18.3M
{
337
18.3M
    if (func->func_version < FUNC_VERSION_FIRST_VALID) {
338
        // Version was never set or has already been cleared.
339
62.9k
        return;
340
62.9k
    }
341
18.3M
#ifndef Py_GIL_DISABLED
342
18.3M
    struct _func_version_cache_item *slot =
343
18.3M
        get_cache_item(interp, func->func_version);
344
18.3M
    if (slot->func == func) {
345
12.0M
        slot->func = NULL;
346
        // Leave slot->code alone, there may be use for it.
347
12.0M
    }
348
18.3M
#endif
349
18.3M
    func->func_version = FUNC_VERSION_CLEARED;
350
18.3M
}
351
352
// Called when any of the critical function attributes are changed
353
static void
354
_PyFunction_ClearVersion(PyFunctionObject *func)
355
15.2k
{
356
15.2k
    if (func->func_version < FUNC_VERSION_FIRST_VALID) {
357
        // Version was never set or has already been cleared.
358
7.65k
        return;
359
7.65k
    }
360
7.54k
    PyInterpreterState *interp = _PyInterpreterState_GET();
361
7.54k
    _PyEval_StopTheWorld(interp);
362
7.54k
    func_clear_version(interp, func);
363
7.54k
    _PyEval_StartTheWorld(interp);
364
7.54k
}
365
366
void
367
_PyFunction_ClearCodeByVersion(uint32_t version)
368
99.3k
{
369
99.3k
#ifndef Py_GIL_DISABLED
370
99.3k
    PyInterpreterState *interp = _PyInterpreterState_GET();
371
99.3k
    struct _func_version_cache_item *slot = get_cache_item(interp, version);
372
99.3k
    if (slot->code) {
373
81.6k
        assert(PyCode_Check(slot->code));
374
81.6k
        PyCodeObject *code = (PyCodeObject *)slot->code;
375
81.6k
        if (code->co_version == version) {
376
13.4k
            slot->code = NULL;
377
13.4k
            slot->func = NULL;
378
13.4k
        }
379
81.6k
    }
380
99.3k
#endif
381
99.3k
}
382
383
uint32_t
384
_PyFunction_GetVersionForCurrentState(PyFunctionObject *func)
385
246k
{
386
246k
    return func->func_version;
387
246k
}
388
389
PyObject *
390
PyFunction_New(PyObject *code, PyObject *globals)
391
18.3M
{
392
18.3M
    return PyFunction_NewWithQualName(code, globals, NULL);
393
18.3M
}
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
416
{
418
416
    if (!PyFunction_Check(op)) {
419
0
        PyErr_BadInternalCall();
420
0
        return NULL;
421
0
    }
422
416
    return ((PyFunctionObject *) op) -> func_module;
423
416
}
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
15.0k
{
536
15.0k
    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.8k
    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.8k
    assert(PyDict_Check(op->func_annotations));
577
14.8k
    return op->func_annotations;
578
14.8k
}
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
349k
{
636
349k
    PyFunctionObject *op = _PyFunction_CAST(self);
637
349k
    if (PySys_Audit("object.__getattr__", "Os", op, "__code__") < 0) {
638
0
        return NULL;
639
0
    }
640
641
349k
    return Py_NewRef(op->func_code);
642
349k
}
643
644
static int
645
func_set_code(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
646
7.51k
{
647
7.51k
    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.51k
    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.51k
    if (PySys_Audit("object.__setattr__", "OsO",
658
7.51k
                    op, "__code__", value) < 0) {
659
0
        return -1;
660
0
    }
661
662
7.51k
    int nfree = ((PyCodeObject *)value)->co_nfreevars;
663
7.51k
    Py_ssize_t nclosure = (op->func_closure == NULL ? 0 :
664
7.51k
                                        PyTuple_GET_SIZE(op->func_closure));
665
7.51k
    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.51k
    PyObject *func_code = PyFunction_GET_CODE(op);
675
7.51k
    int old_flags = ((PyCodeObject *)func_code)->co_flags;
676
7.51k
    int new_flags = ((PyCodeObject *)value)->co_flags;
677
7.51k
    int mask = CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR;
678
7.51k
    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.51k
    handle_func_event(PyFunction_EVENT_MODIFY_CODE, op, value);
688
7.51k
    _PyFunction_ClearVersion(op);
689
7.51k
    Py_XSETREF(op->func_code, Py_NewRef(value));
690
7.51k
    return 0;
691
7.51k
}
692
693
static PyObject *
694
func_get_name(PyObject *self, void *Py_UNUSED(ignored))
695
113k
{
696
113k
    PyFunctionObject *op = _PyFunction_CAST(self);
697
113k
    return Py_NewRef(op->func_name);
698
113k
}
699
700
static int
701
func_set_name(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
702
16.1k
{
703
16.1k
    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
16.1k
    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
16.1k
    Py_XSETREF(op->func_name, Py_NewRef(value));
712
16.1k
    return 0;
713
16.1k
}
714
715
static PyObject *
716
func_get_qualname(PyObject *self, void *Py_UNUSED(ignored))
717
13.3k
{
718
13.3k
    PyFunctionObject *op = _PyFunction_CAST(self);
719
13.3k
    return Py_NewRef(op->func_qualname);
720
13.3k
}
721
722
static int
723
func_set_qualname(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
724
10.0k
{
725
10.0k
    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
10.0k
    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
10.0k
    handle_func_event(PyFunction_EVENT_MODIFY_QUALNAME, (PyFunctionObject *) op, value);
734
10.0k
    Py_XSETREF(op->func_qualname, Py_NewRef(value));
735
10.0k
    return 0;
736
10.0k
}
737
738
static PyObject *
739
func_get_defaults(PyObject *self, void *Py_UNUSED(ignored))
740
55.8k
{
741
55.8k
    PyFunctionObject *op = _PyFunction_CAST(self);
742
55.8k
    if (PySys_Audit("object.__getattr__", "Os", op, "__defaults__") < 0) {
743
0
        return NULL;
744
0
    }
745
55.8k
    if (op->func_defaults == NULL) {
746
55.7k
        Py_RETURN_NONE;
747
55.7k
    }
748
136
    return Py_NewRef(op->func_defaults);
749
55.8k
}
750
751
static int
752
func_set_defaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
753
7.54k
{
754
    /* Legal to del f.func_defaults.
755
     * Can only set func_defaults to NULL or a tuple. */
756
7.54k
    PyFunctionObject *op = _PyFunction_CAST(self);
757
7.54k
    if (value == Py_None)
758
0
        value = NULL;
759
7.54k
    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.54k
    if (value) {
765
7.54k
        if (PySys_Audit("object.__setattr__", "OsO",
766
7.54k
                        op, "__defaults__", value) < 0) {
767
0
            return -1;
768
0
        }
769
7.54k
    } else if (PySys_Audit("object.__delattr__", "Os",
770
0
                           op, "__defaults__") < 0) {
771
0
        return -1;
772
0
    }
773
774
7.54k
    handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS, op, value);
775
7.54k
    _PyFunction_ClearVersion(op);
776
7.54k
    Py_XSETREF(op->func_defaults, Py_XNewRef(value));
777
7.54k
    return 0;
778
7.54k
}
779
780
static PyObject *
781
func_get_kwdefaults(PyObject *self, void *Py_UNUSED(ignored))
782
55.8k
{
783
55.8k
    PyFunctionObject *op = _PyFunction_CAST(self);
784
55.8k
    if (PySys_Audit("object.__getattr__", "Os",
785
55.8k
                    op, "__kwdefaults__") < 0) {
786
0
        return NULL;
787
0
    }
788
55.8k
    if (op->func_kwdefaults == NULL) {
789
55.6k
        Py_RETURN_NONE;
790
55.6k
    }
791
160
    return Py_NewRef(op->func_kwdefaults);
792
55.8k
}
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
8.29k
{
835
8.29k
    if (self->func_annotate == NULL) {
836
614
        Py_RETURN_NONE;
837
614
    }
838
7.68k
    return Py_NewRef(self->func_annotate);
839
8.29k
}
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
8.04k
{
851
8.04k
    if (value == NULL) {
852
0
        PyErr_SetString(PyExc_TypeError,
853
0
            "__annotate__ cannot be deleted");
854
0
        return -1;
855
0
    }
856
8.04k
    if (Py_IsNone(value)) {
857
402
        Py_XSETREF(self->func_annotate, value);
858
402
        return 0;
859
402
    }
860
7.64k
    else if (PyCallable_Check(value)) {
861
7.64k
        Py_XSETREF(self->func_annotate, Py_XNewRef(value));
862
7.64k
        Py_CLEAR(self->func_annotations);
863
7.64k
        return 0;
864
7.64k
    }
865
0
    else {
866
0
        PyErr_SetString(PyExc_TypeError,
867
0
            "__annotate__ must be callable or None");
868
0
        return -1;
869
0
    }
870
8.04k
}
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
15.0k
{
884
15.0k
    PyObject *d = NULL;
885
15.0k
    if (self->func_annotations == NULL &&
886
7.78k
        (self->func_annotate == NULL || !PyCallable_Check(self->func_annotate))) {
887
7.53k
        self->func_annotations = PyDict_New();
888
7.53k
        if (self->func_annotations == NULL)
889
0
            return NULL;
890
7.53k
    }
891
15.0k
    d = func_get_annotation_dict(self);
892
15.0k
    return Py_XNewRef(d);
893
15.0k
}
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.51k
{
905
7.51k
    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.51k
    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.51k
    Py_XSETREF(self->func_annotations, Py_XNewRef(value));
916
7.51k
    Py_CLEAR(self->func_annotate);
917
7.51k
    return 0;
918
7.51k
}
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
8.20k
{
932
8.20k
    if (self->func_typeparams == NULL) {
933
8.13k
        return PyTuple_New(0);
934
8.13k
    }
935
936
8.20k
    assert(PyTuple_Check(self->func_typeparams));
937
76
    return Py_NewRef(self->func_typeparams);
938
8.20k
}
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.93k
{
950
    /* Not legal to del f.__type_params__ or to set it to anything
951
     * other than a tuple object. */
952
7.93k
    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.93k
    Py_XSETREF(self->func_typeparams, Py_NewRef(value));
958
7.93k
    return 0;
959
7.93k
}
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
37
{
1020
37
    PyFunctionObject *newfunc;
1021
37
    Py_ssize_t nclosure;
1022
1023
37
    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
37
    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
37
    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
37
    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
37
    nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
1053
37
    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
37
    if (nclosure) {
1058
37
        Py_ssize_t i;
1059
74
        for (i = 0; i < nclosure; i++) {
1060
37
            PyObject *o = PyTuple_GET_ITEM(closure, i);
1061
37
            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
37
        }
1067
37
    }
1068
37
    if (PySys_Audit("function.__new__", "O", code) < 0) {
1069
0
        return NULL;
1070
0
    }
1071
1072
37
    newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
1073
37
                                                 globals);
1074
37
    if (newfunc == NULL) {
1075
0
        return NULL;
1076
0
    }
1077
37
    if (name != Py_None) {
1078
0
        Py_SETREF(newfunc->func_name, Py_NewRef(name));
1079
0
    }
1080
37
    if (defaults != Py_None) {
1081
0
        newfunc->func_defaults = Py_NewRef(defaults);
1082
0
    }
1083
37
    if (closure != Py_None) {
1084
37
        newfunc->func_closure = Py_NewRef(closure);
1085
37
    }
1086
37
    if (kwdefaults != Py_None) {
1087
0
        newfunc->func_kwdefaults = Py_NewRef(kwdefaults);
1088
0
    }
1089
1090
37
    return (PyObject *)newfunc;
1091
37
}
1092
1093
static int
1094
func_clear(PyObject *self)
1095
18.3M
{
1096
18.3M
    PyFunctionObject *op = _PyFunction_CAST(self);
1097
18.3M
    func_clear_version(_PyInterpreterState_GET(), op);
1098
18.3M
    PyObject *globals = op->func_globals;
1099
18.3M
    op->func_globals = NULL;
1100
18.3M
    if (globals != NULL) {
1101
18.3M
        _Py_DECREF_DICT(globals);
1102
18.3M
    }
1103
18.3M
    PyObject *builtins = op->func_builtins;
1104
18.3M
    op->func_builtins = NULL;
1105
18.3M
    if (builtins != NULL) {
1106
18.3M
        _Py_DECREF_BUILTINS(builtins);
1107
18.3M
    }
1108
18.3M
    Py_CLEAR(op->func_module);
1109
18.3M
    Py_CLEAR(op->func_defaults);
1110
18.3M
    Py_CLEAR(op->func_kwdefaults);
1111
18.3M
    Py_CLEAR(op->func_doc);
1112
18.3M
    Py_CLEAR(op->func_dict);
1113
18.3M
    Py_CLEAR(op->func_closure);
1114
18.3M
    Py_CLEAR(op->func_annotations);
1115
18.3M
    Py_CLEAR(op->func_annotate);
1116
18.3M
    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
18.3M
    Py_SETREF(op->func_name, &_Py_STR(empty));
1123
18.3M
    Py_SETREF(op->func_qualname, &_Py_STR(empty));
1124
18.3M
    return 0;
1125
18.3M
}
1126
1127
static void
1128
func_dealloc(PyObject *self)
1129
18.3M
{
1130
18.3M
    PyFunctionObject *op = _PyFunction_CAST(self);
1131
18.3M
    _PyObject_ResurrectStart(self);
1132
18.3M
    handle_func_event(PyFunction_EVENT_DESTROY, op, NULL);
1133
18.3M
    if (_PyObject_ResurrectEnd(self)) {
1134
0
        return;
1135
0
    }
1136
18.3M
    _PyObject_GC_UNTRACK(op);
1137
18.3M
    FT_CLEAR_WEAKREFS(self, op->func_weakreflist);
1138
18.3M
    (void)func_clear((PyObject*)op);
1139
    // These aren't cleared by func_clear().
1140
18.3M
    _Py_DECREF_CODE((PyCodeObject *)op->func_code);
1141
18.3M
    Py_DECREF(op->func_name);
1142
18.3M
    Py_DECREF(op->func_qualname);
1143
18.3M
    PyObject_GC_Del(op);
1144
18.3M
}
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.77M
{
1157
5.77M
    PyFunctionObject *f = _PyFunction_CAST(self);
1158
5.77M
    Py_VISIT(f->func_code);
1159
5.77M
    Py_VISIT(f->func_globals);
1160
5.77M
    Py_VISIT(f->func_builtins);
1161
5.77M
    Py_VISIT(f->func_module);
1162
5.77M
    Py_VISIT(f->func_defaults);
1163
5.77M
    Py_VISIT(f->func_kwdefaults);
1164
5.77M
    Py_VISIT(f->func_doc);
1165
5.77M
    Py_VISIT(f->func_name);
1166
5.77M
    Py_VISIT(f->func_dict);
1167
5.77M
    Py_VISIT(f->func_closure);
1168
5.77M
    Py_VISIT(f->func_annotations);
1169
5.77M
    Py_VISIT(f->func_annotate);
1170
5.77M
    Py_VISIT(f->func_typeparams);
1171
5.77M
    Py_VISIT(f->func_qualname);
1172
5.77M
    return 0;
1173
5.77M
}
1174
1175
/* Bind a function to an object */
1176
static PyObject *
1177
func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
1178
24.6M
{
1179
24.6M
    if (obj == Py_None || obj == NULL) {
1180
6.62k
        return Py_NewRef(func);
1181
6.62k
    }
1182
24.6M
    return PyMethod_New(func, obj);
1183
24.6M
}
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
19.6k
{
1290
19.6k
    PyObject *value;
1291
19.6k
    int res = PyObject_GetOptionalAttr(wrapped, name, &value);
1292
19.6k
    if (value != NULL) {
1293
19.6k
        res = PyObject_SetAttr(wrapper, name, value);
1294
19.6k
        Py_DECREF(value);
1295
19.6k
    }
1296
19.6k
    return res;
1297
19.6k
}
1298
1299
// Similar to functools.wraps(wrapper, wrapped)
1300
static int
1301
functools_wraps(PyObject *wrapper, PyObject *wrapped)
1302
4.91k
{
1303
4.91k
#define COPY_ATTR(ATTR) \
1304
19.6k
    do { \
1305
19.6k
        if (functools_copy_attr(wrapper, wrapped, &_Py_ID(ATTR)) < 0) { \
1306
0
            return -1; \
1307
0
        } \
1308
19.6k
    } while (0) \
1309
4.91k
1310
4.91k
    COPY_ATTR(__module__);
1311
4.91k
    COPY_ATTR(__name__);
1312
4.91k
    COPY_ATTR(__qualname__);
1313
4.91k
    COPY_ATTR(__doc__);
1314
4.91k
    return 0;
1315
1316
4.91k
#undef COPY_ATTR
1317
4.91k
}
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
549k
    (assert(PyObject_TypeCheck((cm), &PyClassMethod_Type)), \
1412
549k
     _Py_CAST(classmethod*, cm))
1413
1414
static void
1415
cm_dealloc(PyObject *self)
1416
73
{
1417
73
    classmethod *cm = _PyClassMethod_CAST(self);
1418
73
    _PyObject_GC_UNTRACK((PyObject *)cm);
1419
73
    Py_XDECREF(cm->cm_callable);
1420
73
    Py_XDECREF(cm->cm_dict);
1421
73
    Py_TYPE(cm)->tp_free((PyObject *)cm);
1422
73
}
1423
1424
static int
1425
cm_traverse(PyObject *self, visitproc visit, void *arg)
1426
102k
{
1427
102k
    classmethod *cm = _PyClassMethod_CAST(self);
1428
102k
    Py_VISIT(cm->cm_callable);
1429
102k
    Py_VISIT(cm->cm_dict);
1430
102k
    return 0;
1431
102k
}
1432
1433
static int
1434
cm_clear(PyObject *self)
1435
49
{
1436
49
    classmethod *cm = _PyClassMethod_CAST(self);
1437
49
    Py_CLEAR(cm->cm_callable);
1438
49
    Py_CLEAR(cm->cm_dict);
1439
49
    return 0;
1440
49
}
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.25k
{
1455
6.25k
    assert(callable != NULL);
1456
6.25k
    if (cm->cm_callable == callable) {
1457
        // cm_init() sets the same callable than cm_new()
1458
3.09k
        return 0;
1459
3.09k
    }
1460
1461
3.16k
    Py_XSETREF(cm->cm_callable, Py_NewRef(callable));
1462
3.16k
    return functools_wraps((PyObject *)cm, cm->cm_callable);
1463
6.25k
}
1464
1465
static PyObject *
1466
cm_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1467
3.09k
{
1468
3.09k
    if (!_PyArg_NoKeywords("classmethod", kwds)) {
1469
0
        return NULL;
1470
0
    }
1471
3.09k
    PyObject *callable;  // borrowed ref
1472
3.09k
    if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable)) {
1473
0
        return NULL;
1474
0
    }
1475
1476
3.09k
    classmethod *cm = (classmethod *)PyType_GenericAlloc(type, 0);
1477
3.09k
    if (cm == NULL) {
1478
0
        return NULL;
1479
0
    }
1480
3.09k
    _PyObject_SetDeferredRefcount((PyObject *)cm);
1481
3.09k
    if (cm_set_callable(cm, callable) < 0) {
1482
0
        Py_DECREF(cm);
1483
0
        return NULL;
1484
0
    }
1485
3.09k
    return (PyObject *)cm;
1486
3.09k
}
1487
1488
static int
1489
cm_init(PyObject *self, PyObject *args, PyObject *kwds)
1490
3.09k
{
1491
3.09k
    if (!_PyArg_NoKeywords("classmethod", kwds)) {
1492
0
        return -1;
1493
0
    }
1494
3.09k
    PyObject *callable;  // borrowed ref
1495
3.09k
    if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable)) {
1496
0
        return -1;
1497
0
    }
1498
1499
3.09k
    classmethod *cm = (classmethod *)self;
1500
3.09k
    return cm_set_callable(cm, callable);
1501
3.09k
}
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.32k
{
1512
1.32k
    classmethod *cm = _PyClassMethod_CAST(self);
1513
1.32k
    int res = _PyObject_IsAbstract(cm->cm_callable);
1514
1.32k
    if (res == -1) {
1515
0
        return NULL;
1516
0
    }
1517
1.32k
    else if (res) {
1518
0
        Py_RETURN_TRUE;
1519
0
    }
1520
1.32k
    Py_RETURN_FALSE;
1521
1.32k
}
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
77
{
1638
77
    classmethod *cm = (classmethod *)
1639
77
        PyType_GenericAlloc(&PyClassMethod_Type, 0);
1640
77
    if (cm == NULL) {
1641
0
        return NULL;
1642
0
    }
1643
77
    if (cm_set_callable(cm, callable) < 0) {
1644
0
        Py_DECREF(cm);
1645
0
        return NULL;
1646
0
    }
1647
77
    return (PyObject *)cm;
1648
77
}
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
16.5M
    (assert(PyObject_TypeCheck((cm), &PyStaticMethod_Type)), \
1677
16.5M
     _Py_CAST(staticmethod*, cm))
1678
1679
static void
1680
sm_dealloc(PyObject *self)
1681
120
{
1682
120
    staticmethod *sm = _PyStaticMethod_CAST(self);
1683
120
    _PyObject_GC_UNTRACK((PyObject *)sm);
1684
120
    Py_XDECREF(sm->sm_callable);
1685
120
    Py_XDECREF(sm->sm_dict);
1686
120
    Py_TYPE(sm)->tp_free((PyObject *)sm);
1687
120
}
1688
1689
static int
1690
sm_traverse(PyObject *self, visitproc visit, void *arg)
1691
49.6k
{
1692
49.6k
    staticmethod *sm = _PyStaticMethod_CAST(self);
1693
49.6k
    Py_VISIT(sm->sm_callable);
1694
49.6k
    Py_VISIT(sm->sm_dict);
1695
49.6k
    return 0;
1696
49.6k
}
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
16.0k
{
1710
16.0k
    staticmethod *sm = (staticmethod *)self;
1711
16.0k
    return Py_NewRef(sm->sm_callable);
1712
16.0k
}
1713
1714
static int
1715
sm_set_callable(staticmethod *sm, PyObject *callable)
1716
2.57k
{
1717
2.57k
    assert(callable != NULL);
1718
2.57k
    if (sm->sm_callable == callable) {
1719
        // sm_init() sets the same callable than sm_new()
1720
829
        return 0;
1721
829
    }
1722
1723
1.74k
    Py_XSETREF(sm->sm_callable, Py_NewRef(callable));
1724
1.74k
    return functools_wraps((PyObject *)sm, sm->sm_callable);
1725
2.57k
}
1726
1727
static PyObject *
1728
sm_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1729
829
{
1730
829
    if (!_PyArg_NoKeywords("staticmethod", kwds)) {
1731
0
        return NULL;
1732
0
    }
1733
829
    PyObject *callable;  // borrowed ref
1734
829
    if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable)) {
1735
0
        return NULL;
1736
0
    }
1737
1738
829
    staticmethod *sm = (staticmethod *)PyType_GenericAlloc(type, 0);
1739
829
    if (sm == NULL) {
1740
0
        return NULL;
1741
0
    }
1742
829
    _PyObject_SetDeferredRefcount((PyObject *)sm);
1743
829
    if (sm_set_callable(sm, callable) < 0) {
1744
0
        Py_DECREF(sm);
1745
0
        return NULL;
1746
0
    }
1747
829
    return (PyObject *)sm;
1748
829
}
1749
1750
static int
1751
sm_init(PyObject *self, PyObject *args, PyObject *kwds)
1752
829
{
1753
829
    if (!_PyArg_NoKeywords("staticmethod", kwds)) {
1754
0
        return -1;
1755
0
    }
1756
829
    PyObject *callable;  // borrowed ref
1757
829
    if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable)) {
1758
0
        return -1;
1759
0
    }
1760
1761
829
    staticmethod *sm = (staticmethod *)self;
1762
829
    return sm_set_callable(sm, callable);
1763
829
}
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
73
{
1781
73
    staticmethod *sm = _PyStaticMethod_CAST(self);
1782
73
    int res = _PyObject_IsAbstract(sm->sm_callable);
1783
73
    if (res == -1) {
1784
0
        return NULL;
1785
0
    }
1786
73
    else if (res) {
1787
0
        Py_RETURN_TRUE;
1788
0
    }
1789
73
    Py_RETURN_FALSE;
1790
73
}
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
917
{
1904
917
    staticmethod *sm = (staticmethod *)
1905
917
        PyType_GenericAlloc(&PyStaticMethod_Type, 0);
1906
917
    if (sm == NULL) {
1907
0
        return NULL;
1908
0
    }
1909
917
    _PyObject_SetDeferredRefcount((PyObject *)sm);
1910
917
    if (sm_set_callable(sm, callable) < 0) {
1911
0
        Py_DECREF(sm);
1912
0
        return NULL;
1913
0
    }
1914
917
    return (PyObject *)sm;
1915
917
}
1916
1917
PyObject *
1918
_PyClassMethod_GetFunc(PyObject *self)
1919
445k
{
1920
445k
    classmethod *cm = _PyClassMethod_CAST(self);
1921
445k
    return cm->cm_callable;
1922
445k
}
1923
1924
PyObject *
1925
_PyStaticMethod_GetFunc(PyObject *self)
1926
16.4M
{
1927
    staticmethod *sm = _PyStaticMethod_CAST(self);
1928
16.4M
    return sm->sm_callable;
1929
16.4M
}