Coverage Report

Created: 2025-08-29 06:15

/src/cpython/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
26.4M
{
55
26.4M
    assert(Py_REFCNT(func) > 0);
56
26.4M
    PyInterpreterState *interp = _PyInterpreterState_GET();
57
26.4M
    assert(interp->_initialized);
58
26.4M
    if (interp->active_func_watchers) {
59
0
        notify_func_watchers(interp, event, func, new_value);
60
0
    }
61
26.4M
    switch (event) {
62
0
        case PyFunction_EVENT_MODIFY_CODE:
63
4
        case PyFunction_EVENT_MODIFY_DEFAULTS:
64
4
        case PyFunction_EVENT_MODIFY_KWDEFAULTS:
65
4
            RARE_EVENT_INTERP_INC(interp, func_modification);
66
4
            break;
67
26.4M
        default:
68
26.4M
            break;
69
26.4M
    }
70
26.4M
}
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
1.11k
{
109
1.11k
    PyObject *module;
110
1.11k
    if (PyDict_GetItemRef(constr->fc_globals, &_Py_ID(__name__), &module) < 0) {
111
0
        return NULL;
112
0
    }
113
114
1.11k
    PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
115
1.11k
    if (op == NULL) {
116
0
        Py_XDECREF(module);
117
0
        return NULL;
118
0
    }
119
1.11k
    _Py_INCREF_DICT(constr->fc_globals);
120
1.11k
    op->func_globals = constr->fc_globals;
121
1.11k
    _Py_INCREF_BUILTINS(constr->fc_builtins);
122
1.11k
    op->func_builtins = constr->fc_builtins;
123
1.11k
    op->func_name = Py_NewRef(constr->fc_name);
124
1.11k
    op->func_qualname = Py_NewRef(constr->fc_qualname);
125
1.11k
    _Py_INCREF_CODE((PyCodeObject *)constr->fc_code);
126
1.11k
    op->func_code = constr->fc_code;
127
1.11k
    op->func_defaults = Py_XNewRef(constr->fc_defaults);
128
1.11k
    op->func_kwdefaults = Py_XNewRef(constr->fc_kwdefaults);
129
1.11k
    op->func_closure = Py_XNewRef(constr->fc_closure);
130
1.11k
    op->func_doc = Py_NewRef(Py_None);
131
1.11k
    op->func_dict = NULL;
132
1.11k
    op->func_weakreflist = NULL;
133
1.11k
    op->func_module = module;
134
1.11k
    op->func_annotations = NULL;
135
1.11k
    op->func_annotate = NULL;
136
1.11k
    op->func_typeparams = NULL;
137
1.11k
    op->vectorcall = _PyFunction_Vectorcall;
138
1.11k
    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
1.11k
    _PyObject_GC_TRACK(op);
143
1.11k
    handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
144
1.11k
    return op;
145
1.11k
}
146
147
PyObject *
148
PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
149
13.2M
{
150
13.2M
    assert(globals != NULL);
151
13.2M
    assert(PyDict_Check(globals));
152
13.2M
    _Py_INCREF_DICT(globals);
153
154
13.2M
    PyCodeObject *code_obj = (PyCodeObject *)code;
155
13.2M
    _Py_INCREF_CODE(code_obj);
156
157
13.2M
    assert(code_obj->co_name != NULL);
158
13.2M
    PyObject *name = Py_NewRef(code_obj->co_name);
159
160
13.2M
    if (!qualname) {
161
13.2M
        qualname = code_obj->co_qualname;
162
13.2M
    }
163
13.2M
    assert(qualname != NULL);
164
13.2M
    Py_INCREF(qualname);
165
166
13.2M
    PyObject *consts = code_obj->co_consts;
167
13.2M
    assert(PyTuple_Check(consts));
168
13.2M
    PyObject *doc;
169
13.2M
    if (code_obj->co_flags & CO_HAS_DOCSTRING) {
170
27.6k
        assert(PyTuple_Size(consts) >= 1);
171
27.6k
        doc = PyTuple_GetItem(consts, 0);
172
27.6k
        if (!PyUnicode_Check(doc)) {
173
0
            doc = Py_None;
174
0
        }
175
27.6k
    }
176
13.1M
    else {
177
13.1M
        doc = Py_None;
178
13.1M
    }
179
13.2M
    Py_INCREF(doc);
180
181
    // __module__: Use globals['__name__'] if it exists, or NULL.
182
13.2M
    PyObject *module;
183
13.2M
    PyObject *builtins = NULL;
184
13.2M
    if (PyDict_GetItemRef(globals, &_Py_ID(__name__), &module) < 0) {
185
0
        goto error;
186
0
    }
187
188
13.2M
    builtins = _PyDict_LoadBuiltinsFromGlobals(globals);
189
13.2M
    if (builtins == NULL) {
190
0
        goto error;
191
0
    }
192
193
13.2M
    PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
194
13.2M
    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
13.2M
    op->func_globals = globals;
201
13.2M
    op->func_builtins = builtins;
202
13.2M
    op->func_name = name;
203
13.2M
    op->func_qualname = qualname;
204
13.2M
    op->func_code = (PyObject*)code_obj;
205
13.2M
    op->func_defaults = NULL;    // No default positional arguments
206
13.2M
    op->func_kwdefaults = NULL;  // No default keyword arguments
207
13.2M
    op->func_closure = NULL;
208
13.2M
    op->func_doc = doc;
209
13.2M
    op->func_dict = NULL;
210
13.2M
    op->func_weakreflist = NULL;
211
13.2M
    op->func_module = module;
212
13.2M
    op->func_annotations = NULL;
213
13.2M
    op->func_annotate = NULL;
214
13.2M
    op->func_typeparams = NULL;
215
13.2M
    op->vectorcall = _PyFunction_Vectorcall;
216
13.2M
    op->func_version = FUNC_VERSION_UNSET;
217
13.2M
    if (((code_obj->co_flags & CO_NESTED) == 0) ||
218
13.2M
        (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
29.0k
        _PyObject_SetDeferredRefcount((PyObject *)op);
226
29.0k
    }
227
13.2M
    _PyObject_GC_TRACK(op);
228
13.2M
    handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
229
13.2M
    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
13.2M
}
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
26.4M
{
304
26.4M
    return interp->func_state.func_version_cache +
305
26.4M
           (version % FUNC_VERSION_CACHE_SIZE);
306
26.4M
}
307
#endif
308
309
void
310
_PyFunction_SetVersion(PyFunctionObject *func, uint32_t version)
311
13.2M
{
312
13.2M
    assert(func->func_version == FUNC_VERSION_UNSET);
313
13.2M
    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
13.2M
    func->func_version = version;
317
13.2M
#ifndef Py_GIL_DISABLED
318
13.2M
    PyInterpreterState *interp = _PyInterpreterState_GET();
319
13.2M
    struct _func_version_cache_item *slot = get_cache_item(interp, version);
320
13.2M
    slot->func = func;
321
13.2M
    slot->code = func->func_code;
322
13.2M
#endif
323
13.2M
}
324
325
static void
326
func_clear_version(PyInterpreterState *interp, PyFunctionObject *func)
327
13.1M
{
328
13.1M
    if (func->func_version < FUNC_VERSION_FIRST_VALID) {
329
        // Version was never set or has already been cleared.
330
1.65k
        return;
331
1.65k
    }
332
13.1M
#ifndef Py_GIL_DISABLED
333
13.1M
    struct _func_version_cache_item *slot =
334
13.1M
        get_cache_item(interp, func->func_version);
335
13.1M
    if (slot->func == func) {
336
8.17M
        slot->func = NULL;
337
        // Leave slot->code alone, there may be use for it.
338
8.17M
    }
339
13.1M
#endif
340
13.1M
    func->func_version = FUNC_VERSION_CLEARED;
341
13.1M
}
342
343
// Called when any of the critical function attributes are changed
344
static void
345
_PyFunction_ClearVersion(PyFunctionObject *func)
346
4
{
347
4
    if (func->func_version < FUNC_VERSION_FIRST_VALID) {
348
        // Version was never set or has already been cleared.
349
0
        return;
350
0
    }
351
4
    PyInterpreterState *interp = _PyInterpreterState_GET();
352
4
    _PyEval_StopTheWorld(interp);
353
4
    func_clear_version(interp, func);
354
4
    _PyEval_StartTheWorld(interp);
355
4
}
356
357
void
358
_PyFunction_ClearCodeByVersion(uint32_t version)
359
8.09k
{
360
8.09k
#ifndef Py_GIL_DISABLED
361
8.09k
    PyInterpreterState *interp = _PyInterpreterState_GET();
362
8.09k
    struct _func_version_cache_item *slot = get_cache_item(interp, version);
363
8.09k
    if (slot->code) {
364
6.10k
        assert(PyCode_Check(slot->code));
365
6.10k
        PyCodeObject *code = (PyCodeObject *)slot->code;
366
6.10k
        if (code->co_version == version) {
367
6.10k
            slot->code = NULL;
368
6.10k
            slot->func = NULL;
369
6.10k
        }
370
6.10k
    }
371
8.09k
#endif
372
8.09k
}
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
17.7k
{
403
17.7k
    return func->func_version;
404
17.7k
}
405
406
PyObject *
407
PyFunction_New(PyObject *code, PyObject *globals)
408
13.2M
{
409
13.2M
    return PyFunction_NewWithQualName(code, globals, NULL);
410
13.2M
}
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
66
{
435
66
    if (!PyFunction_Check(op)) {
436
0
        PyErr_BadInternalCall();
437
0
        return NULL;
438
0
    }
439
66
    return ((PyFunctionObject *) op) -> func_module;
440
66
}
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
8
{
553
8
    if (op->func_annotations == NULL) {
554
8
        if (op->func_annotate == NULL || !PyCallable_Check(op->func_annotate)) {
555
0
            Py_RETURN_NONE;
556
0
        }
557
8
        PyObject *one = _PyLong_GetOne();
558
8
        PyObject *ann_dict = _PyObject_CallOneArg(op->func_annotate, one);
559
8
        if (ann_dict == NULL) {
560
0
            return NULL;
561
0
        }
562
8
        if (!PyDict_Check(ann_dict)) {
563
0
            PyErr_Format(PyExc_TypeError,
564
0
                         "__annotate__() must return a dict, not %T",
565
0
                         ann_dict);
566
0
            Py_DECREF(ann_dict);
567
0
            return NULL;
568
0
        }
569
8
        Py_XSETREF(op->func_annotations, ann_dict);
570
8
        return ann_dict;
571
8
    }
572
0
    if (PyTuple_CheckExact(op->func_annotations)) {
573
0
        PyObject *ann_tuple = op->func_annotations;
574
0
        PyObject *ann_dict = PyDict_New();
575
0
        if (ann_dict == NULL) {
576
0
            return NULL;
577
0
        }
578
579
0
        assert(PyTuple_GET_SIZE(ann_tuple) % 2 == 0);
580
581
0
        for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(ann_tuple); i += 2) {
582
0
            int err = PyDict_SetItem(ann_dict,
583
0
                                     PyTuple_GET_ITEM(ann_tuple, i),
584
0
                                     PyTuple_GET_ITEM(ann_tuple, i + 1));
585
586
0
            if (err < 0) {
587
0
                Py_DECREF(ann_dict);
588
0
                return NULL;
589
0
            }
590
0
        }
591
0
        Py_SETREF(op->func_annotations, ann_dict);
592
0
    }
593
0
    assert(PyDict_Check(op->func_annotations));
594
0
    return op->func_annotations;
595
0
}
596
597
PyObject *
598
PyFunction_GetAnnotations(PyObject *op)
599
0
{
600
0
    if (!PyFunction_Check(op)) {
601
0
        PyErr_BadInternalCall();
602
0
        return NULL;
603
0
    }
604
0
    return func_get_annotation_dict((PyFunctionObject *)op);
605
0
}
606
607
int
608
PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)
609
0
{
610
0
    if (!PyFunction_Check(op)) {
611
0
        PyErr_BadInternalCall();
612
0
        return -1;
613
0
    }
614
0
    if (annotations == Py_None)
615
0
        annotations = NULL;
616
0
    else if (annotations && PyDict_Check(annotations)) {
617
0
        Py_INCREF(annotations);
618
0
    }
619
0
    else {
620
0
        PyErr_SetString(PyExc_SystemError,
621
0
                        "non-dict annotations");
622
0
        return -1;
623
0
    }
624
0
    PyFunctionObject *func = (PyFunctionObject *)op;
625
0
    Py_XSETREF(func->func_annotations, annotations);
626
0
    Py_CLEAR(func->func_annotate);
627
0
    return 0;
628
0
}
629
630
/* Methods */
631
632
#define OFF(x) offsetof(PyFunctionObject, x)
633
634
static PyMemberDef func_memberlist[] = {
635
    {"__closure__",   _Py_T_OBJECT,     OFF(func_closure), Py_READONLY},
636
    {"__doc__",       _Py_T_OBJECT,     OFF(func_doc), 0},
637
    {"__globals__",   _Py_T_OBJECT,     OFF(func_globals), Py_READONLY},
638
    {"__module__",    _Py_T_OBJECT,     OFF(func_module), 0},
639
    {"__builtins__",  _Py_T_OBJECT,     OFF(func_builtins), Py_READONLY},
640
    {NULL}  /* Sentinel */
641
};
642
643
/*[clinic input]
644
class function "PyFunctionObject *" "&PyFunction_Type"
645
[clinic start generated code]*/
646
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=70af9c90aa2e71b0]*/
647
648
#include "clinic/funcobject.c.h"
649
650
static PyObject *
651
func_get_code(PyObject *self, void *Py_UNUSED(ignored))
652
40
{
653
40
    PyFunctionObject *op = _PyFunction_CAST(self);
654
40
    if (PySys_Audit("object.__getattr__", "Os", op, "__code__") < 0) {
655
0
        return NULL;
656
0
    }
657
658
40
    return Py_NewRef(op->func_code);
659
40
}
660
661
static int
662
func_set_code(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
663
0
{
664
0
    PyFunctionObject *op = _PyFunction_CAST(self);
665
666
    /* Not legal to del f.func_code or to set it to anything
667
     * other than a code object. */
668
0
    if (value == NULL || !PyCode_Check(value)) {
669
0
        PyErr_SetString(PyExc_TypeError,
670
0
                        "__code__ must be set to a code object");
671
0
        return -1;
672
0
    }
673
674
0
    if (PySys_Audit("object.__setattr__", "OsO",
675
0
                    op, "__code__", value) < 0) {
676
0
        return -1;
677
0
    }
678
679
0
    int nfree = ((PyCodeObject *)value)->co_nfreevars;
680
0
    Py_ssize_t nclosure = (op->func_closure == NULL ? 0 :
681
0
                                        PyTuple_GET_SIZE(op->func_closure));
682
0
    if (nclosure != nfree) {
683
0
        PyErr_Format(PyExc_ValueError,
684
0
                     "%U() requires a code object with %zd free vars,"
685
0
                     " not %zd",
686
0
                     op->func_name,
687
0
                     nclosure, nfree);
688
0
        return -1;
689
0
    }
690
691
0
    PyObject *func_code = PyFunction_GET_CODE(op);
692
0
    int old_flags = ((PyCodeObject *)func_code)->co_flags;
693
0
    int new_flags = ((PyCodeObject *)value)->co_flags;
694
0
    int mask = CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR;
695
0
    if ((old_flags & mask) != (new_flags & mask)) {
696
0
        if (PyErr_Warn(PyExc_DeprecationWarning,
697
0
            "Assigning a code object of non-matching type is deprecated "
698
0
            "(e.g., from a generator to a plain function)") < 0)
699
0
        {
700
0
            return -1;
701
0
        }
702
0
    }
703
704
0
    handle_func_event(PyFunction_EVENT_MODIFY_CODE, op, value);
705
0
    _PyFunction_ClearVersion(op);
706
0
    Py_XSETREF(op->func_code, Py_NewRef(value));
707
0
    return 0;
708
0
}
709
710
static PyObject *
711
func_get_name(PyObject *self, void *Py_UNUSED(ignored))
712
2.27k
{
713
2.27k
    PyFunctionObject *op = _PyFunction_CAST(self);
714
2.27k
    return Py_NewRef(op->func_name);
715
2.27k
}
716
717
static int
718
func_set_name(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
719
327
{
720
327
    PyFunctionObject *op = _PyFunction_CAST(self);
721
    /* Not legal to del f.func_name or to set it to anything
722
     * other than a string object. */
723
327
    if (value == NULL || !PyUnicode_Check(value)) {
724
0
        PyErr_SetString(PyExc_TypeError,
725
0
                        "__name__ must be set to a string object");
726
0
        return -1;
727
0
    }
728
327
    Py_XSETREF(op->func_name, Py_NewRef(value));
729
327
    return 0;
730
327
}
731
732
static PyObject *
733
func_get_qualname(PyObject *self, void *Py_UNUSED(ignored))
734
1.73k
{
735
1.73k
    PyFunctionObject *op = _PyFunction_CAST(self);
736
1.73k
    return Py_NewRef(op->func_qualname);
737
1.73k
}
738
739
static int
740
func_set_qualname(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
741
693
{
742
693
    PyFunctionObject *op = _PyFunction_CAST(self);
743
    /* Not legal to del f.__qualname__ or to set it to anything
744
     * other than a string object. */
745
693
    if (value == NULL || !PyUnicode_Check(value)) {
746
0
        PyErr_SetString(PyExc_TypeError,
747
0
                        "__qualname__ must be set to a string object");
748
0
        return -1;
749
0
    }
750
693
    Py_XSETREF(op->func_qualname, Py_NewRef(value));
751
693
    return 0;
752
693
}
753
754
static PyObject *
755
func_get_defaults(PyObject *self, void *Py_UNUSED(ignored))
756
8
{
757
8
    PyFunctionObject *op = _PyFunction_CAST(self);
758
8
    if (PySys_Audit("object.__getattr__", "Os", op, "__defaults__") < 0) {
759
0
        return NULL;
760
0
    }
761
8
    if (op->func_defaults == NULL) {
762
6
        Py_RETURN_NONE;
763
6
    }
764
2
    return Py_NewRef(op->func_defaults);
765
8
}
766
767
static int
768
func_set_defaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
769
4
{
770
    /* Legal to del f.func_defaults.
771
     * Can only set func_defaults to NULL or a tuple. */
772
4
    PyFunctionObject *op = _PyFunction_CAST(self);
773
4
    if (value == Py_None)
774
0
        value = NULL;
775
4
    if (value != NULL && !PyTuple_Check(value)) {
776
0
        PyErr_SetString(PyExc_TypeError,
777
0
                        "__defaults__ must be set to a tuple object");
778
0
        return -1;
779
0
    }
780
4
    if (value) {
781
4
        if (PySys_Audit("object.__setattr__", "OsO",
782
4
                        op, "__defaults__", value) < 0) {
783
0
            return -1;
784
0
        }
785
4
    } else if (PySys_Audit("object.__delattr__", "Os",
786
0
                           op, "__defaults__") < 0) {
787
0
        return -1;
788
0
    }
789
790
4
    handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS, op, value);
791
4
    _PyFunction_ClearVersion(op);
792
4
    Py_XSETREF(op->func_defaults, Py_XNewRef(value));
793
4
    return 0;
794
4
}
795
796
static PyObject *
797
func_get_kwdefaults(PyObject *self, void *Py_UNUSED(ignored))
798
8
{
799
8
    PyFunctionObject *op = _PyFunction_CAST(self);
800
8
    if (PySys_Audit("object.__getattr__", "Os",
801
8
                    op, "__kwdefaults__") < 0) {
802
0
        return NULL;
803
0
    }
804
8
    if (op->func_kwdefaults == NULL) {
805
2
        Py_RETURN_NONE;
806
2
    }
807
6
    return Py_NewRef(op->func_kwdefaults);
808
8
}
809
810
static int
811
func_set_kwdefaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
812
0
{
813
0
    PyFunctionObject *op = _PyFunction_CAST(self);
814
0
    if (value == Py_None)
815
0
        value = NULL;
816
    /* Legal to del f.func_kwdefaults.
817
     * Can only set func_kwdefaults to NULL or a dict. */
818
0
    if (value != NULL && !PyDict_Check(value)) {
819
0
        PyErr_SetString(PyExc_TypeError,
820
0
            "__kwdefaults__ must be set to a dict object");
821
0
        return -1;
822
0
    }
823
0
    if (value) {
824
0
        if (PySys_Audit("object.__setattr__", "OsO",
825
0
                        op, "__kwdefaults__", value) < 0) {
826
0
            return -1;
827
0
        }
828
0
    } else if (PySys_Audit("object.__delattr__", "Os",
829
0
                           op, "__kwdefaults__") < 0) {
830
0
        return -1;
831
0
    }
832
833
0
    handle_func_event(PyFunction_EVENT_MODIFY_KWDEFAULTS, op, value);
834
0
    _PyFunction_ClearVersion(op);
835
0
    Py_XSETREF(op->func_kwdefaults, Py_XNewRef(value));
836
0
    return 0;
837
0
}
838
839
/*[clinic input]
840
@critical_section
841
@getter
842
function.__annotate__
843
844
Get the code object for a function.
845
[clinic start generated code]*/
846
847
static PyObject *
848
function___annotate___get_impl(PyFunctionObject *self)
849
/*[clinic end generated code: output=5ec7219ff2bda9e6 input=7f3db11e3c3329f3]*/
850
121
{
851
121
    if (self->func_annotate == NULL) {
852
121
        Py_RETURN_NONE;
853
121
    }
854
0
    return Py_NewRef(self->func_annotate);
855
121
}
856
857
/*[clinic input]
858
@critical_section
859
@setter
860
function.__annotate__
861
[clinic start generated code]*/
862
863
static int
864
function___annotate___set_impl(PyFunctionObject *self, PyObject *value)
865
/*[clinic end generated code: output=05b7dfc07ada66cd input=eb6225e358d97448]*/
866
65
{
867
65
    if (value == NULL) {
868
0
        PyErr_SetString(PyExc_TypeError,
869
0
            "__annotate__ cannot be deleted");
870
0
        return -1;
871
0
    }
872
65
    if (Py_IsNone(value)) {
873
65
        Py_XSETREF(self->func_annotate, value);
874
65
        return 0;
875
65
    }
876
0
    else if (PyCallable_Check(value)) {
877
0
        Py_XSETREF(self->func_annotate, Py_XNewRef(value));
878
0
        Py_CLEAR(self->func_annotations);
879
0
        return 0;
880
0
    }
881
0
    else {
882
0
        PyErr_SetString(PyExc_TypeError,
883
0
            "__annotate__ must be callable or None");
884
0
        return -1;
885
0
    }
886
65
}
887
888
/*[clinic input]
889
@critical_section
890
@getter
891
function.__annotations__
892
893
Dict of annotations in a function object.
894
[clinic start generated code]*/
895
896
static PyObject *
897
function___annotations___get_impl(PyFunctionObject *self)
898
/*[clinic end generated code: output=a4cf4c884c934cbb input=92643d7186c1ad0c]*/
899
8
{
900
8
    PyObject *d = NULL;
901
8
    if (self->func_annotations == NULL &&
902
8
        (self->func_annotate == NULL || !PyCallable_Check(self->func_annotate))) {
903
0
        self->func_annotations = PyDict_New();
904
0
        if (self->func_annotations == NULL)
905
0
            return NULL;
906
0
    }
907
8
    d = func_get_annotation_dict(self);
908
8
    return Py_XNewRef(d);
909
8
}
910
911
/*[clinic input]
912
@critical_section
913
@setter
914
function.__annotations__
915
[clinic start generated code]*/
916
917
static int
918
function___annotations___set_impl(PyFunctionObject *self, PyObject *value)
919
/*[clinic end generated code: output=a61795d4a95eede4 input=5302641f686f0463]*/
920
0
{
921
0
    if (value == Py_None)
922
0
        value = NULL;
923
    /* Legal to del f.func_annotations.
924
     * Can only set func_annotations to NULL (through C api)
925
     * or a dict. */
926
0
    if (value != NULL && !PyDict_Check(value)) {
927
0
        PyErr_SetString(PyExc_TypeError,
928
0
            "__annotations__ must be set to a dict object");
929
0
        return -1;
930
0
    }
931
0
    Py_XSETREF(self->func_annotations, Py_XNewRef(value));
932
0
    Py_CLEAR(self->func_annotate);
933
0
    return 0;
934
0
}
935
936
/*[clinic input]
937
@critical_section
938
@getter
939
function.__type_params__
940
941
Get the declared type parameters for a function.
942
[clinic start generated code]*/
943
944
static PyObject *
945
function___type_params___get_impl(PyFunctionObject *self)
946
/*[clinic end generated code: output=eb844d7ffca517a8 input=0864721484293724]*/
947
121
{
948
121
    if (self->func_typeparams == NULL) {
949
121
        return PyTuple_New(0);
950
121
    }
951
952
0
    assert(PyTuple_Check(self->func_typeparams));
953
0
    return Py_NewRef(self->func_typeparams);
954
121
}
955
956
/*[clinic input]
957
@critical_section
958
@setter
959
function.__type_params__
960
[clinic start generated code]*/
961
962
static int
963
function___type_params___set_impl(PyFunctionObject *self, PyObject *value)
964
/*[clinic end generated code: output=038b4cda220e56fb input=3862fbd4db2b70e8]*/
965
65
{
966
    /* Not legal to del f.__type_params__ or to set it to anything
967
     * other than a tuple object. */
968
65
    if (value == NULL || !PyTuple_Check(value)) {
969
0
        PyErr_SetString(PyExc_TypeError,
970
0
                        "__type_params__ must be set to a tuple");
971
0
        return -1;
972
0
    }
973
65
    Py_XSETREF(self->func_typeparams, Py_NewRef(value));
974
65
    return 0;
975
65
}
976
977
PyObject *
978
_Py_set_function_type_params(PyThreadState *Py_UNUSED(ignored), PyObject *func,
979
                             PyObject *type_params)
980
0
{
981
0
    assert(PyFunction_Check(func));
982
0
    assert(PyTuple_Check(type_params));
983
0
    PyFunctionObject *f = (PyFunctionObject *)func;
984
0
    Py_XSETREF(f->func_typeparams, Py_NewRef(type_params));
985
0
    return Py_NewRef(func);
986
0
}
987
988
static PyGetSetDef func_getsetlist[] = {
989
    {"__code__", func_get_code, func_set_code},
990
    {"__defaults__", func_get_defaults, func_set_defaults},
991
    {"__kwdefaults__", func_get_kwdefaults, func_set_kwdefaults},
992
    FUNCTION___ANNOTATIONS___GETSETDEF
993
    FUNCTION___ANNOTATE___GETSETDEF
994
    {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
995
    {"__name__", func_get_name, func_set_name},
996
    {"__qualname__", func_get_qualname, func_set_qualname},
997
    FUNCTION___TYPE_PARAMS___GETSETDEF
998
    {NULL} /* Sentinel */
999
};
1000
1001
/* function.__new__() maintains the following invariants for closures.
1002
   The closure must correspond to the free variables of the code object.
1003
1004
   if len(code.co_freevars) == 0:
1005
       closure = NULL
1006
   else:
1007
       len(closure) == len(code.co_freevars)
1008
   for every elt in closure, type(elt) == cell
1009
*/
1010
1011
/*[clinic input]
1012
@classmethod
1013
function.__new__ as func_new
1014
    code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1015
        a code object
1016
    globals: object(subclass_of="&PyDict_Type")
1017
        the globals dictionary
1018
    name: object = None
1019
        a string that overrides the name from the code object
1020
    argdefs as defaults: object = None
1021
        a tuple that specifies the default argument values
1022
    closure: object = None
1023
        a tuple that supplies the bindings for free variables
1024
    kwdefaults: object = None
1025
        a dictionary that specifies the default keyword argument values
1026
1027
Create a function object.
1028
[clinic start generated code]*/
1029
1030
static PyObject *
1031
func_new_impl(PyTypeObject *type, PyCodeObject *code, PyObject *globals,
1032
              PyObject *name, PyObject *defaults, PyObject *closure,
1033
              PyObject *kwdefaults)
1034
/*[clinic end generated code: output=de72f4c22ac57144 input=20c9c9f04ad2d3f2]*/
1035
0
{
1036
0
    PyFunctionObject *newfunc;
1037
0
    Py_ssize_t nclosure;
1038
1039
0
    if (name != Py_None && !PyUnicode_Check(name)) {
1040
0
        PyErr_SetString(PyExc_TypeError,
1041
0
                        "arg 3 (name) must be None or string");
1042
0
        return NULL;
1043
0
    }
1044
0
    if (defaults != Py_None && !PyTuple_Check(defaults)) {
1045
0
        PyErr_SetString(PyExc_TypeError,
1046
0
                        "arg 4 (defaults) must be None or tuple");
1047
0
        return NULL;
1048
0
    }
1049
0
    if (!PyTuple_Check(closure)) {
1050
0
        if (code->co_nfreevars && closure == Py_None) {
1051
0
            PyErr_SetString(PyExc_TypeError,
1052
0
                            "arg 5 (closure) must be tuple");
1053
0
            return NULL;
1054
0
        }
1055
0
        else if (closure != Py_None) {
1056
0
            PyErr_SetString(PyExc_TypeError,
1057
0
                "arg 5 (closure) must be None or tuple");
1058
0
            return NULL;
1059
0
        }
1060
0
    }
1061
0
    if (kwdefaults != Py_None && !PyDict_Check(kwdefaults)) {
1062
0
        PyErr_SetString(PyExc_TypeError,
1063
0
                        "arg 6 (kwdefaults) must be None or dict");
1064
0
        return NULL;
1065
0
    }
1066
1067
    /* check that the closure is well-formed */
1068
0
    nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
1069
0
    if (code->co_nfreevars != nclosure)
1070
0
        return PyErr_Format(PyExc_ValueError,
1071
0
                            "%U requires closure of length %zd, not %zd",
1072
0
                            code->co_name, code->co_nfreevars, nclosure);
1073
0
    if (nclosure) {
1074
0
        Py_ssize_t i;
1075
0
        for (i = 0; i < nclosure; i++) {
1076
0
            PyObject *o = PyTuple_GET_ITEM(closure, i);
1077
0
            if (!PyCell_Check(o)) {
1078
0
                return PyErr_Format(PyExc_TypeError,
1079
0
                    "arg 5 (closure) expected cell, found %s",
1080
0
                                    Py_TYPE(o)->tp_name);
1081
0
            }
1082
0
        }
1083
0
    }
1084
0
    if (PySys_Audit("function.__new__", "O", code) < 0) {
1085
0
        return NULL;
1086
0
    }
1087
1088
0
    newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
1089
0
                                                 globals);
1090
0
    if (newfunc == NULL) {
1091
0
        return NULL;
1092
0
    }
1093
0
    if (name != Py_None) {
1094
0
        Py_SETREF(newfunc->func_name, Py_NewRef(name));
1095
0
    }
1096
0
    if (defaults != Py_None) {
1097
0
        newfunc->func_defaults = Py_NewRef(defaults);
1098
0
    }
1099
0
    if (closure != Py_None) {
1100
0
        newfunc->func_closure = Py_NewRef(closure);
1101
0
    }
1102
0
    if (kwdefaults != Py_None) {
1103
0
        newfunc->func_kwdefaults = Py_NewRef(kwdefaults);
1104
0
    }
1105
1106
0
    return (PyObject *)newfunc;
1107
0
}
1108
1109
static int
1110
func_clear(PyObject *self)
1111
13.1M
{
1112
13.1M
    PyFunctionObject *op = _PyFunction_CAST(self);
1113
13.1M
    func_clear_version(_PyInterpreterState_GET(), op);
1114
13.1M
    PyObject *globals = op->func_globals;
1115
13.1M
    op->func_globals = NULL;
1116
13.1M
    if (globals != NULL) {
1117
13.1M
        _Py_DECREF_DICT(globals);
1118
13.1M
    }
1119
13.1M
    PyObject *builtins = op->func_builtins;
1120
13.1M
    op->func_builtins = NULL;
1121
13.1M
    if (builtins != NULL) {
1122
13.1M
        _Py_DECREF_BUILTINS(builtins);
1123
13.1M
    }
1124
13.1M
    Py_CLEAR(op->func_module);
1125
13.1M
    Py_CLEAR(op->func_defaults);
1126
13.1M
    Py_CLEAR(op->func_kwdefaults);
1127
13.1M
    Py_CLEAR(op->func_doc);
1128
13.1M
    Py_CLEAR(op->func_dict);
1129
13.1M
    Py_CLEAR(op->func_closure);
1130
13.1M
    Py_CLEAR(op->func_annotations);
1131
13.1M
    Py_CLEAR(op->func_annotate);
1132
13.1M
    Py_CLEAR(op->func_typeparams);
1133
    // Don't Py_CLEAR(op->func_code), since code is always required
1134
    // to be non-NULL. Similarly, name and qualname shouldn't be NULL.
1135
    // However, name and qualname could be str subclasses, so they
1136
    // could have reference cycles. The solution is to replace them
1137
    // with a genuinely immutable string.
1138
13.1M
    Py_SETREF(op->func_name, &_Py_STR(empty));
1139
13.1M
    Py_SETREF(op->func_qualname, &_Py_STR(empty));
1140
13.1M
    return 0;
1141
13.1M
}
1142
1143
static void
1144
func_dealloc(PyObject *self)
1145
13.1M
{
1146
13.1M
    PyFunctionObject *op = _PyFunction_CAST(self);
1147
13.1M
    _PyObject_ResurrectStart(self);
1148
13.1M
    handle_func_event(PyFunction_EVENT_DESTROY, op, NULL);
1149
13.1M
    if (_PyObject_ResurrectEnd(self)) {
1150
0
        return;
1151
0
    }
1152
13.1M
    _PyObject_GC_UNTRACK(op);
1153
13.1M
    FT_CLEAR_WEAKREFS(self, op->func_weakreflist);
1154
13.1M
    (void)func_clear((PyObject*)op);
1155
    // These aren't cleared by func_clear().
1156
13.1M
    _Py_DECREF_CODE((PyCodeObject *)op->func_code);
1157
13.1M
    Py_DECREF(op->func_name);
1158
13.1M
    Py_DECREF(op->func_qualname);
1159
13.1M
    PyObject_GC_Del(op);
1160
13.1M
}
1161
1162
static PyObject*
1163
func_repr(PyObject *self)
1164
0
{
1165
0
    PyFunctionObject *op = _PyFunction_CAST(self);
1166
0
    return PyUnicode_FromFormat("<function %U at %p>",
1167
0
                                op->func_qualname, op);
1168
0
}
1169
1170
static int
1171
func_traverse(PyObject *self, visitproc visit, void *arg)
1172
10.6M
{
1173
10.6M
    PyFunctionObject *f = _PyFunction_CAST(self);
1174
10.6M
    Py_VISIT(f->func_code);
1175
10.6M
    Py_VISIT(f->func_globals);
1176
10.6M
    Py_VISIT(f->func_builtins);
1177
10.6M
    Py_VISIT(f->func_module);
1178
10.6M
    Py_VISIT(f->func_defaults);
1179
10.6M
    Py_VISIT(f->func_kwdefaults);
1180
10.6M
    Py_VISIT(f->func_doc);
1181
10.6M
    Py_VISIT(f->func_name);
1182
10.6M
    Py_VISIT(f->func_dict);
1183
10.6M
    Py_VISIT(f->func_closure);
1184
10.6M
    Py_VISIT(f->func_annotations);
1185
10.6M
    Py_VISIT(f->func_annotate);
1186
10.6M
    Py_VISIT(f->func_typeparams);
1187
10.6M
    Py_VISIT(f->func_qualname);
1188
10.6M
    return 0;
1189
10.6M
}
1190
1191
/* Bind a function to an object */
1192
static PyObject *
1193
func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
1194
21.3M
{
1195
21.3M
    if (obj == Py_None || obj == NULL) {
1196
2.24k
        return Py_NewRef(func);
1197
2.24k
    }
1198
21.3M
    return PyMethod_New(func, obj);
1199
21.3M
}
1200
1201
PyTypeObject PyFunction_Type = {
1202
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1203
    "function",
1204
    sizeof(PyFunctionObject),
1205
    0,
1206
    func_dealloc,                               /* tp_dealloc */
1207
    offsetof(PyFunctionObject, vectorcall),     /* tp_vectorcall_offset */
1208
    0,                                          /* tp_getattr */
1209
    0,                                          /* tp_setattr */
1210
    0,                                          /* tp_as_async */
1211
    func_repr,                                  /* tp_repr */
1212
    0,                                          /* tp_as_number */
1213
    0,                                          /* tp_as_sequence */
1214
    0,                                          /* tp_as_mapping */
1215
    0,                                          /* tp_hash */
1216
    PyVectorcall_Call,                          /* tp_call */
1217
    0,                                          /* tp_str */
1218
    0,                                          /* tp_getattro */
1219
    0,                                          /* tp_setattro */
1220
    0,                                          /* tp_as_buffer */
1221
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1222
    Py_TPFLAGS_HAVE_VECTORCALL |
1223
    Py_TPFLAGS_METHOD_DESCRIPTOR,               /* tp_flags */
1224
    func_new__doc__,                            /* tp_doc */
1225
    func_traverse,                              /* tp_traverse */
1226
    func_clear,                                 /* tp_clear */
1227
    0,                                          /* tp_richcompare */
1228
    offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
1229
    0,                                          /* tp_iter */
1230
    0,                                          /* tp_iternext */
1231
    0,                                          /* tp_methods */
1232
    func_memberlist,                            /* tp_members */
1233
    func_getsetlist,                            /* tp_getset */
1234
    0,                                          /* tp_base */
1235
    0,                                          /* tp_dict */
1236
    func_descr_get,                             /* tp_descr_get */
1237
    0,                                          /* tp_descr_set */
1238
    offsetof(PyFunctionObject, func_dict),      /* tp_dictoffset */
1239
    0,                                          /* tp_init */
1240
    0,                                          /* tp_alloc */
1241
    func_new,                                   /* tp_new */
1242
};
1243
1244
1245
int
1246
_PyFunction_VerifyStateless(PyThreadState *tstate, PyObject *func)
1247
0
{
1248
0
    assert(!PyErr_Occurred());
1249
0
    assert(PyFunction_Check(func));
1250
1251
    // Check the globals.
1252
0
    PyObject *globalsns = PyFunction_GET_GLOBALS(func);
1253
0
    if (globalsns != NULL && !PyDict_Check(globalsns)) {
1254
0
        _PyErr_Format(tstate, PyExc_TypeError,
1255
0
                      "unsupported globals %R", globalsns);
1256
0
        return -1;
1257
0
    }
1258
    // Check the builtins.
1259
0
    PyObject *builtinsns = _PyFunction_GET_BUILTINS(func);
1260
0
    if (builtinsns != NULL && !PyDict_Check(builtinsns)) {
1261
0
        _PyErr_Format(tstate, PyExc_TypeError,
1262
0
                      "unsupported builtins %R", builtinsns);
1263
0
        return -1;
1264
0
    }
1265
    // Disallow __defaults__.
1266
0
    PyObject *defaults = PyFunction_GET_DEFAULTS(func);
1267
0
    if (defaults != NULL) {
1268
0
        assert(PyTuple_Check(defaults));  // per PyFunction_New()
1269
0
        if (PyTuple_GET_SIZE(defaults) > 0) {
1270
0
            _PyErr_SetString(tstate, PyExc_ValueError,
1271
0
                             "defaults not supported");
1272
0
            return -1;
1273
0
        }
1274
0
    }
1275
    // Disallow __kwdefaults__.
1276
0
    PyObject *kwdefaults = PyFunction_GET_KW_DEFAULTS(func);
1277
0
    if (kwdefaults != NULL) {
1278
0
        assert(PyDict_Check(kwdefaults));  // per PyFunction_New()
1279
0
        if (PyDict_Size(kwdefaults) > 0) {
1280
0
            _PyErr_SetString(tstate, PyExc_ValueError,
1281
0
                             "keyword defaults not supported");
1282
0
            return -1;
1283
0
        }
1284
0
    }
1285
    // Disallow __closure__.
1286
0
    PyObject *closure = PyFunction_GET_CLOSURE(func);
1287
0
    if (closure != NULL) {
1288
0
        assert(PyTuple_Check(closure));  // per PyFunction_New()
1289
0
        if (PyTuple_GET_SIZE(closure) > 0) {
1290
0
            _PyErr_SetString(tstate, PyExc_ValueError, "closures not supported");
1291
0
            return -1;
1292
0
        }
1293
0
    }
1294
    // Check the code.
1295
0
    PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
1296
0
    if (_PyCode_VerifyStateless(tstate, co, NULL, globalsns, builtinsns) < 0) {
1297
0
        return -1;
1298
0
    }
1299
0
    return 0;
1300
0
}
1301
1302
1303
static int
1304
functools_copy_attr(PyObject *wrapper, PyObject *wrapped, PyObject *name)
1305
5.96k
{
1306
5.96k
    PyObject *value;
1307
5.96k
    int res = PyObject_GetOptionalAttr(wrapped, name, &value);
1308
5.96k
    if (value != NULL) {
1309
5.96k
        res = PyObject_SetAttr(wrapper, name, value);
1310
5.96k
        Py_DECREF(value);
1311
5.96k
    }
1312
5.96k
    return res;
1313
5.96k
}
1314
1315
// Similar to functools.wraps(wrapper, wrapped)
1316
static int
1317
functools_wraps(PyObject *wrapper, PyObject *wrapped)
1318
1.49k
{
1319
1.49k
#define COPY_ATTR(ATTR) \
1320
5.96k
    do { \
1321
5.96k
        if (functools_copy_attr(wrapper, wrapped, &_Py_ID(ATTR)) < 0) { \
1322
0
            return -1; \
1323
0
        } \
1324
5.96k
    } while (0) \
1325
1.49k
1326
1.49k
    COPY_ATTR(__module__);
1327
1.49k
    COPY_ATTR(__name__);
1328
1.49k
    COPY_ATTR(__qualname__);
1329
1.49k
    COPY_ATTR(__doc__);
1330
1.49k
    return 0;
1331
1332
1.49k
#undef COPY_ATTR
1333
1.49k
}
1334
1335
// Used for wrapping __annotations__ and __annotate__ on classmethod
1336
// and staticmethod objects.
1337
static PyObject *
1338
descriptor_get_wrapped_attribute(PyObject *wrapped, PyObject *obj, PyObject *name)
1339
0
{
1340
0
    PyObject *dict = PyObject_GenericGetDict(obj, NULL);
1341
0
    if (dict == NULL) {
1342
0
        return NULL;
1343
0
    }
1344
0
    PyObject *res;
1345
0
    if (PyDict_GetItemRef(dict, name, &res) < 0) {
1346
0
        Py_DECREF(dict);
1347
0
        return NULL;
1348
0
    }
1349
0
    if (res != NULL) {
1350
0
        Py_DECREF(dict);
1351
0
        return res;
1352
0
    }
1353
0
    res = PyObject_GetAttr(wrapped, name);
1354
0
    if (res == NULL) {
1355
0
        Py_DECREF(dict);
1356
0
        return NULL;
1357
0
    }
1358
0
    if (PyDict_SetItem(dict, name, res) < 0) {
1359
0
        Py_DECREF(dict);
1360
0
        Py_DECREF(res);
1361
0
        return NULL;
1362
0
    }
1363
0
    Py_DECREF(dict);
1364
0
    return res;
1365
0
}
1366
1367
static int
1368
descriptor_set_wrapped_attribute(PyObject *oobj, PyObject *name, PyObject *value,
1369
                                 char *type_name)
1370
0
{
1371
0
    PyObject *dict = PyObject_GenericGetDict(oobj, NULL);
1372
0
    if (dict == NULL) {
1373
0
        return -1;
1374
0
    }
1375
0
    if (value == NULL) {
1376
0
        if (PyDict_DelItem(dict, name) < 0) {
1377
0
            if (PyErr_ExceptionMatches(PyExc_KeyError)) {
1378
0
                PyErr_Clear();
1379
0
                PyErr_Format(PyExc_AttributeError,
1380
0
                             "'%.200s' object has no attribute '%U'",
1381
0
                             type_name, name);
1382
0
                Py_DECREF(dict);
1383
0
                return -1;
1384
0
            }
1385
0
            else {
1386
0
                Py_DECREF(dict);
1387
0
                return -1;
1388
0
            }
1389
0
        }
1390
0
        Py_DECREF(dict);
1391
0
        return 0;
1392
0
    }
1393
0
    else {
1394
0
        Py_DECREF(dict);
1395
0
        return PyDict_SetItem(dict, name, value);
1396
0
    }
1397
0
}
1398
1399
1400
/* Class method object */
1401
1402
/* A class method receives the class as implicit first argument,
1403
   just like an instance method receives the instance.
1404
   To declare a class method, use this idiom:
1405
1406
     class C:
1407
         @classmethod
1408
         def f(cls, arg1, arg2, argN):
1409
             ...
1410
1411
   It can be called either on the class (e.g. C.f()) or on an instance
1412
   (e.g. C().f()); the instance is ignored except for its class.
1413
   If a class method is called for a derived class, the derived class
1414
   object is passed as the implied first argument.
1415
1416
   Class methods are different than C++ or Java static methods.
1417
   If you want those, see static methods below.
1418
*/
1419
1420
typedef struct {
1421
    PyObject_HEAD
1422
    PyObject *cm_callable;
1423
    PyObject *cm_dict;
1424
} classmethod;
1425
1426
#define _PyClassMethod_CAST(cm) \
1427
450k
    (assert(PyObject_TypeCheck((cm), &PyClassMethod_Type)), \
1428
450k
     _Py_CAST(classmethod*, cm))
1429
1430
static void
1431
cm_dealloc(PyObject *self)
1432
36
{
1433
36
    classmethod *cm = _PyClassMethod_CAST(self);
1434
36
    _PyObject_GC_UNTRACK((PyObject *)cm);
1435
36
    Py_XDECREF(cm->cm_callable);
1436
36
    Py_XDECREF(cm->cm_dict);
1437
36
    Py_TYPE(cm)->tp_free((PyObject *)cm);
1438
36
}
1439
1440
static int
1441
cm_traverse(PyObject *self, visitproc visit, void *arg)
1442
449k
{
1443
449k
    classmethod *cm = _PyClassMethod_CAST(self);
1444
449k
    Py_VISIT(cm->cm_callable);
1445
449k
    Py_VISIT(cm->cm_dict);
1446
449k
    return 0;
1447
449k
}
1448
1449
static int
1450
cm_clear(PyObject *self)
1451
24
{
1452
24
    classmethod *cm = _PyClassMethod_CAST(self);
1453
24
    Py_CLEAR(cm->cm_callable);
1454
24
    Py_CLEAR(cm->cm_dict);
1455
24
    return 0;
1456
24
}
1457
1458
1459
static PyObject *
1460
cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
1461
472k
{
1462
472k
    classmethod *cm = (classmethod *)self;
1463
1464
472k
    if (cm->cm_callable == NULL) {
1465
0
        PyErr_SetString(PyExc_RuntimeError,
1466
0
                        "uninitialized classmethod object");
1467
0
        return NULL;
1468
0
    }
1469
472k
    if (type == NULL)
1470
0
        type = (PyObject *)(Py_TYPE(obj));
1471
472k
    return PyMethod_New(cm->cm_callable, type);
1472
472k
}
1473
1474
static int
1475
cm_init(PyObject *self, PyObject *args, PyObject *kwds)
1476
1.20k
{
1477
1.20k
    classmethod *cm = (classmethod *)self;
1478
1.20k
    PyObject *callable;
1479
1480
1.20k
    if (!_PyArg_NoKeywords("classmethod", kwds))
1481
0
        return -1;
1482
1.20k
    if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable))
1483
0
        return -1;
1484
1.20k
    Py_XSETREF(cm->cm_callable, Py_NewRef(callable));
1485
1486
1.20k
    if (functools_wraps((PyObject *)cm, cm->cm_callable) < 0) {
1487
0
        return -1;
1488
0
    }
1489
1.20k
    return 0;
1490
1.20k
}
1491
1492
static PyMemberDef cm_memberlist[] = {
1493
    {"__func__", _Py_T_OBJECT, offsetof(classmethod, cm_callable), Py_READONLY},
1494
    {"__wrapped__", _Py_T_OBJECT, offsetof(classmethod, cm_callable), Py_READONLY},
1495
    {NULL}  /* Sentinel */
1496
};
1497
1498
static PyObject *
1499
cm_get___isabstractmethod__(PyObject *self, void *closure)
1500
504
{
1501
504
    classmethod *cm = _PyClassMethod_CAST(self);
1502
504
    int res = _PyObject_IsAbstract(cm->cm_callable);
1503
504
    if (res == -1) {
1504
0
        return NULL;
1505
0
    }
1506
504
    else if (res) {
1507
0
        Py_RETURN_TRUE;
1508
0
    }
1509
504
    Py_RETURN_FALSE;
1510
504
}
1511
1512
static PyObject *
1513
cm_get___annotations__(PyObject *self, void *closure)
1514
0
{
1515
0
    classmethod *cm = _PyClassMethod_CAST(self);
1516
0
    return descriptor_get_wrapped_attribute(cm->cm_callable, self, &_Py_ID(__annotations__));
1517
0
}
1518
1519
static int
1520
cm_set___annotations__(PyObject *self, PyObject *value, void *closure)
1521
0
{
1522
0
    return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotations__), value, "classmethod");
1523
0
}
1524
1525
static PyObject *
1526
cm_get___annotate__(PyObject *self, void *closure)
1527
0
{
1528
0
    classmethod *cm = _PyClassMethod_CAST(self);
1529
0
    return descriptor_get_wrapped_attribute(cm->cm_callable, self, &_Py_ID(__annotate__));
1530
0
}
1531
1532
static int
1533
cm_set___annotate__(PyObject *self, PyObject *value, void *closure)
1534
0
{
1535
0
    return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotate__), value, "classmethod");
1536
0
}
1537
1538
1539
static PyGetSetDef cm_getsetlist[] = {
1540
    {"__isabstractmethod__", cm_get___isabstractmethod__, NULL, NULL, NULL},
1541
    {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
1542
    {"__annotations__", cm_get___annotations__, cm_set___annotations__, NULL, NULL},
1543
    {"__annotate__", cm_get___annotate__, cm_set___annotate__, NULL, NULL},
1544
    {NULL} /* Sentinel */
1545
};
1546
1547
static PyMethodDef cm_methodlist[] = {
1548
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, NULL},
1549
    {NULL} /* Sentinel */
1550
};
1551
1552
static PyObject*
1553
cm_repr(PyObject *self)
1554
0
{
1555
0
    classmethod *cm = _PyClassMethod_CAST(self);
1556
0
    return PyUnicode_FromFormat("<classmethod(%R)>", cm->cm_callable);
1557
0
}
1558
1559
PyDoc_STRVAR(classmethod_doc,
1560
"classmethod(function, /)\n\
1561
--\n\
1562
\n\
1563
Convert a function to be a class method.\n\
1564
\n\
1565
A class method receives the class as implicit first argument,\n\
1566
just like an instance method receives the instance.\n\
1567
To declare a class method, use this idiom:\n\
1568
\n\
1569
  class C:\n\
1570
      @classmethod\n\
1571
      def f(cls, arg1, arg2, argN):\n\
1572
          ...\n\
1573
\n\
1574
It can be called either on the class (e.g. C.f()) or on an instance\n\
1575
(e.g. C().f()).  The instance is ignored except for its class.\n\
1576
If a class method is called for a derived class, the derived class\n\
1577
object is passed as the implied first argument.\n\
1578
\n\
1579
Class methods are different than C++ or Java static methods.\n\
1580
If you want those, see the staticmethod builtin.");
1581
1582
PyTypeObject PyClassMethod_Type = {
1583
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1584
    "classmethod",
1585
    sizeof(classmethod),
1586
    0,
1587
    cm_dealloc,                                 /* tp_dealloc */
1588
    0,                                          /* tp_vectorcall_offset */
1589
    0,                                          /* tp_getattr */
1590
    0,                                          /* tp_setattr */
1591
    0,                                          /* tp_as_async */
1592
    cm_repr,                                    /* tp_repr */
1593
    0,                                          /* tp_as_number */
1594
    0,                                          /* tp_as_sequence */
1595
    0,                                          /* tp_as_mapping */
1596
    0,                                          /* tp_hash */
1597
    0,                                          /* tp_call */
1598
    0,                                          /* tp_str */
1599
    0,                                          /* tp_getattro */
1600
    0,                                          /* tp_setattro */
1601
    0,                                          /* tp_as_buffer */
1602
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1603
    classmethod_doc,                            /* tp_doc */
1604
    cm_traverse,                                /* tp_traverse */
1605
    cm_clear,                                   /* tp_clear */
1606
    0,                                          /* tp_richcompare */
1607
    0,                                          /* tp_weaklistoffset */
1608
    0,                                          /* tp_iter */
1609
    0,                                          /* tp_iternext */
1610
    cm_methodlist,                              /* tp_methods */
1611
    cm_memberlist,                              /* tp_members */
1612
    cm_getsetlist,                              /* tp_getset */
1613
    0,                                          /* tp_base */
1614
    0,                                          /* tp_dict */
1615
    cm_descr_get,                               /* tp_descr_get */
1616
    0,                                          /* tp_descr_set */
1617
    offsetof(classmethod, cm_dict),             /* tp_dictoffset */
1618
    cm_init,                                    /* tp_init */
1619
    PyType_GenericAlloc,                        /* tp_alloc */
1620
    PyType_GenericNew,                          /* tp_new */
1621
    PyObject_GC_Del,                            /* tp_free */
1622
};
1623
1624
PyObject *
1625
PyClassMethod_New(PyObject *callable)
1626
24
{
1627
24
    classmethod *cm = (classmethod *)
1628
24
        PyType_GenericAlloc(&PyClassMethod_Type, 0);
1629
24
    if (cm != NULL) {
1630
24
        cm->cm_callable = Py_NewRef(callable);
1631
24
    }
1632
24
    return (PyObject *)cm;
1633
24
}
1634
1635
1636
/* Static method object */
1637
1638
/* A static method does not receive an implicit first argument.
1639
   To declare a static method, use this idiom:
1640
1641
     class C:
1642
         @staticmethod
1643
         def f(arg1, arg2, argN):
1644
             ...
1645
1646
   It can be called either on the class (e.g. C.f()) or on an instance
1647
   (e.g. C().f()). Both the class and the instance are ignored, and
1648
   neither is passed implicitly as the first argument to the method.
1649
1650
   Static methods in Python are similar to those found in Java or C++.
1651
   For a more advanced concept, see class methods above.
1652
*/
1653
1654
typedef struct {
1655
    PyObject_HEAD
1656
    PyObject *sm_callable;
1657
    PyObject *sm_dict;
1658
} staticmethod;
1659
1660
#define _PyStaticMethod_CAST(cm) \
1661
208k
    (assert(PyObject_TypeCheck((cm), &PyStaticMethod_Type)), \
1662
208k
     _Py_CAST(staticmethod*, cm))
1663
1664
static void
1665
sm_dealloc(PyObject *self)
1666
58
{
1667
58
    staticmethod *sm = _PyStaticMethod_CAST(self);
1668
58
    _PyObject_GC_UNTRACK((PyObject *)sm);
1669
58
    Py_XDECREF(sm->sm_callable);
1670
58
    Py_XDECREF(sm->sm_dict);
1671
58
    Py_TYPE(sm)->tp_free((PyObject *)sm);
1672
58
}
1673
1674
static int
1675
sm_traverse(PyObject *self, visitproc visit, void *arg)
1676
208k
{
1677
208k
    staticmethod *sm = _PyStaticMethod_CAST(self);
1678
208k
    Py_VISIT(sm->sm_callable);
1679
208k
    Py_VISIT(sm->sm_dict);
1680
208k
    return 0;
1681
208k
}
1682
1683
static int
1684
sm_clear(PyObject *self)
1685
0
{
1686
0
    staticmethod *sm = _PyStaticMethod_CAST(self);
1687
0
    Py_CLEAR(sm->sm_callable);
1688
0
    Py_CLEAR(sm->sm_dict);
1689
0
    return 0;
1690
0
}
1691
1692
static PyObject *
1693
sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
1694
11.6M
{
1695
11.6M
    staticmethod *sm = (staticmethod *)self;
1696
1697
11.6M
    if (sm->sm_callable == NULL) {
1698
0
        PyErr_SetString(PyExc_RuntimeError,
1699
0
                        "uninitialized staticmethod object");
1700
0
        return NULL;
1701
0
    }
1702
11.6M
    return Py_NewRef(sm->sm_callable);
1703
11.6M
}
1704
1705
static int
1706
sm_init(PyObject *self, PyObject *args, PyObject *kwds)
1707
288
{
1708
288
    staticmethod *sm = (staticmethod *)self;
1709
288
    PyObject *callable;
1710
1711
288
    if (!_PyArg_NoKeywords("staticmethod", kwds))
1712
0
        return -1;
1713
288
    if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable))
1714
0
        return -1;
1715
288
    Py_XSETREF(sm->sm_callable, Py_NewRef(callable));
1716
1717
288
    if (functools_wraps((PyObject *)sm, sm->sm_callable) < 0) {
1718
0
        return -1;
1719
0
    }
1720
288
    return 0;
1721
288
}
1722
1723
static PyObject*
1724
sm_call(PyObject *callable, PyObject *args, PyObject *kwargs)
1725
0
{
1726
0
    staticmethod *sm = (staticmethod *)callable;
1727
0
    return PyObject_Call(sm->sm_callable, args, kwargs);
1728
0
}
1729
1730
static PyMemberDef sm_memberlist[] = {
1731
    {"__func__", _Py_T_OBJECT, offsetof(staticmethod, sm_callable), Py_READONLY},
1732
    {"__wrapped__", _Py_T_OBJECT, offsetof(staticmethod, sm_callable), Py_READONLY},
1733
    {NULL}  /* Sentinel */
1734
};
1735
1736
static PyObject *
1737
sm_get___isabstractmethod__(PyObject *self, void *closure)
1738
6
{
1739
6
    staticmethod *sm = _PyStaticMethod_CAST(self);
1740
6
    int res = _PyObject_IsAbstract(sm->sm_callable);
1741
6
    if (res == -1) {
1742
0
        return NULL;
1743
0
    }
1744
6
    else if (res) {
1745
0
        Py_RETURN_TRUE;
1746
0
    }
1747
6
    Py_RETURN_FALSE;
1748
6
}
1749
1750
static PyObject *
1751
sm_get___annotations__(PyObject *self, void *closure)
1752
0
{
1753
0
    staticmethod *sm = _PyStaticMethod_CAST(self);
1754
0
    return descriptor_get_wrapped_attribute(sm->sm_callable, self, &_Py_ID(__annotations__));
1755
0
}
1756
1757
static int
1758
sm_set___annotations__(PyObject *self, PyObject *value, void *closure)
1759
0
{
1760
0
    return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotations__), value, "staticmethod");
1761
0
}
1762
1763
static PyObject *
1764
sm_get___annotate__(PyObject *self, void *closure)
1765
0
{
1766
0
    staticmethod *sm = _PyStaticMethod_CAST(self);
1767
0
    return descriptor_get_wrapped_attribute(sm->sm_callable, self, &_Py_ID(__annotate__));
1768
0
}
1769
1770
static int
1771
sm_set___annotate__(PyObject *self, PyObject *value, void *closure)
1772
0
{
1773
0
    return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotate__), value, "staticmethod");
1774
0
}
1775
1776
static PyGetSetDef sm_getsetlist[] = {
1777
    {"__isabstractmethod__", sm_get___isabstractmethod__, NULL, NULL, NULL},
1778
    {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
1779
    {"__annotations__", sm_get___annotations__, sm_set___annotations__, NULL, NULL},
1780
    {"__annotate__", sm_get___annotate__, sm_set___annotate__, NULL, NULL},
1781
    {NULL} /* Sentinel */
1782
};
1783
1784
static PyMethodDef sm_methodlist[] = {
1785
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, NULL},
1786
    {NULL} /* Sentinel */
1787
};
1788
1789
static PyObject*
1790
sm_repr(PyObject *self)
1791
0
{
1792
0
    staticmethod *sm = _PyStaticMethod_CAST(self);
1793
0
    return PyUnicode_FromFormat("<staticmethod(%R)>", sm->sm_callable);
1794
0
}
1795
1796
PyDoc_STRVAR(staticmethod_doc,
1797
"staticmethod(function, /)\n\
1798
--\n\
1799
\n\
1800
Convert a function to be a static method.\n\
1801
\n\
1802
A static method does not receive an implicit first argument.\n\
1803
To declare a static method, use this idiom:\n\
1804
\n\
1805
     class C:\n\
1806
         @staticmethod\n\
1807
         def f(arg1, arg2, argN):\n\
1808
             ...\n\
1809
\n\
1810
It can be called either on the class (e.g. C.f()) or on an instance\n\
1811
(e.g. C().f()). Both the class and the instance are ignored, and\n\
1812
neither is passed implicitly as the first argument to the method.\n\
1813
\n\
1814
Static methods in Python are similar to those found in Java or C++.\n\
1815
For a more advanced concept, see the classmethod builtin.");
1816
1817
PyTypeObject PyStaticMethod_Type = {
1818
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1819
    "staticmethod",
1820
    sizeof(staticmethod),
1821
    0,
1822
    sm_dealloc,                                 /* tp_dealloc */
1823
    0,                                          /* tp_vectorcall_offset */
1824
    0,                                          /* tp_getattr */
1825
    0,                                          /* tp_setattr */
1826
    0,                                          /* tp_as_async */
1827
    sm_repr,                                    /* tp_repr */
1828
    0,                                          /* tp_as_number */
1829
    0,                                          /* tp_as_sequence */
1830
    0,                                          /* tp_as_mapping */
1831
    0,                                          /* tp_hash */
1832
    sm_call,                                    /* tp_call */
1833
    0,                                          /* tp_str */
1834
    0,                                          /* tp_getattro */
1835
    0,                                          /* tp_setattro */
1836
    0,                                          /* tp_as_buffer */
1837
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1838
    staticmethod_doc,                           /* tp_doc */
1839
    sm_traverse,                                /* tp_traverse */
1840
    sm_clear,                                   /* tp_clear */
1841
    0,                                          /* tp_richcompare */
1842
    0,                                          /* tp_weaklistoffset */
1843
    0,                                          /* tp_iter */
1844
    0,                                          /* tp_iternext */
1845
    sm_methodlist,                              /* tp_methods */
1846
    sm_memberlist,                              /* tp_members */
1847
    sm_getsetlist,                              /* tp_getset */
1848
    0,                                          /* tp_base */
1849
    0,                                          /* tp_dict */
1850
    sm_descr_get,                               /* tp_descr_get */
1851
    0,                                          /* tp_descr_set */
1852
    offsetof(staticmethod, sm_dict),            /* tp_dictoffset */
1853
    sm_init,                                    /* tp_init */
1854
    PyType_GenericAlloc,                        /* tp_alloc */
1855
    PyType_GenericNew,                          /* tp_new */
1856
    PyObject_GC_Del,                            /* tp_free */
1857
};
1858
1859
PyObject *
1860
PyStaticMethod_New(PyObject *callable)
1861
316
{
1862
316
    staticmethod *sm = (staticmethod *)
1863
316
        PyType_GenericAlloc(&PyStaticMethod_Type, 0);
1864
316
    if (sm != NULL) {
1865
316
        sm->sm_callable = Py_NewRef(callable);
1866
316
    }
1867
316
    return (PyObject *)sm;
1868
316
}