Coverage Report

Created: 2025-08-09 06:50

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