Coverage Report

Created: 2025-08-24 06:48

/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
75.6k
{
55
75.6k
    assert(Py_REFCNT(func) > 0);
56
75.6k
    PyInterpreterState *interp = _PyInterpreterState_GET();
57
75.6k
    assert(interp->_initialized);
58
75.6k
    if (interp->active_func_watchers) {
59
0
        notify_func_watchers(interp, event, func, new_value);
60
0
    }
61
75.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
75.6k
        default:
68
75.6k
            break;
69
75.6k
    }
70
75.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
655
{
109
655
    PyObject *module;
110
655
    if (PyDict_GetItemRef(constr->fc_globals, &_Py_ID(__name__), &module) < 0) {
111
0
        return NULL;
112
0
    }
113
114
655
    PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
115
655
    if (op == NULL) {
116
0
        Py_XDECREF(module);
117
0
        return NULL;
118
0
    }
119
655
    _Py_INCREF_DICT(constr->fc_globals);
120
655
    op->func_globals = constr->fc_globals;
121
655
    _Py_INCREF_BUILTINS(constr->fc_builtins);
122
655
    op->func_builtins = constr->fc_builtins;
123
655
    op->func_name = Py_NewRef(constr->fc_name);
124
655
    op->func_qualname = Py_NewRef(constr->fc_qualname);
125
655
    _Py_INCREF_CODE((PyCodeObject *)constr->fc_code);
126
655
    op->func_code = constr->fc_code;
127
655
    op->func_defaults = Py_XNewRef(constr->fc_defaults);
128
655
    op->func_kwdefaults = Py_XNewRef(constr->fc_kwdefaults);
129
655
    op->func_closure = Py_XNewRef(constr->fc_closure);
130
655
    op->func_doc = Py_NewRef(Py_None);
131
655
    op->func_dict = NULL;
132
655
    op->func_weakreflist = NULL;
133
655
    op->func_module = module;
134
655
    op->func_annotations = NULL;
135
655
    op->func_annotate = NULL;
136
655
    op->func_typeparams = NULL;
137
655
    op->vectorcall = _PyFunction_Vectorcall;
138
655
    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
655
    _PyObject_GC_TRACK(op);
143
655
    handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
144
655
    return op;
145
655
}
146
147
PyObject *
148
PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
149
46.4k
{
150
46.4k
    assert(globals != NULL);
151
46.4k
    assert(PyDict_Check(globals));
152
46.4k
    _Py_INCREF_DICT(globals);
153
154
46.4k
    PyCodeObject *code_obj = (PyCodeObject *)code;
155
46.4k
    _Py_INCREF_CODE(code_obj);
156
157
46.4k
    assert(code_obj->co_name != NULL);
158
46.4k
    PyObject *name = Py_NewRef(code_obj->co_name);
159
160
46.4k
    if (!qualname) {
161
46.4k
        qualname = code_obj->co_qualname;
162
46.4k
    }
163
46.4k
    assert(qualname != NULL);
164
46.4k
    Py_INCREF(qualname);
165
166
46.4k
    PyObject *consts = code_obj->co_consts;
167
46.4k
    assert(PyTuple_Check(consts));
168
46.4k
    PyObject *doc;
169
46.4k
    if (code_obj->co_flags & CO_HAS_DOCSTRING) {
170
9.68k
        assert(PyTuple_Size(consts) >= 1);
171
9.68k
        doc = PyTuple_GetItem(consts, 0);
172
9.68k
        if (!PyUnicode_Check(doc)) {
173
0
            doc = Py_None;
174
0
        }
175
9.68k
    }
176
36.7k
    else {
177
36.7k
        doc = Py_None;
178
36.7k
    }
179
46.4k
    Py_INCREF(doc);
180
181
    // __module__: Use globals['__name__'] if it exists, or NULL.
182
46.4k
    PyObject *module;
183
46.4k
    PyObject *builtins = NULL;
184
46.4k
    if (PyDict_GetItemRef(globals, &_Py_ID(__name__), &module) < 0) {
185
0
        goto error;
186
0
    }
187
188
46.4k
    builtins = _PyDict_LoadBuiltinsFromGlobals(globals);
189
46.4k
    if (builtins == NULL) {
190
0
        goto error;
191
0
    }
192
193
46.4k
    PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
194
46.4k
    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
46.4k
    op->func_globals = globals;
201
46.4k
    op->func_builtins = builtins;
202
46.4k
    op->func_name = name;
203
46.4k
    op->func_qualname = qualname;
204
46.4k
    op->func_code = (PyObject*)code_obj;
205
46.4k
    op->func_defaults = NULL;    // No default positional arguments
206
46.4k
    op->func_kwdefaults = NULL;  // No default keyword arguments
207
46.4k
    op->func_closure = NULL;
208
46.4k
    op->func_doc = doc;
209
46.4k
    op->func_dict = NULL;
210
46.4k
    op->func_weakreflist = NULL;
211
46.4k
    op->func_module = module;
212
46.4k
    op->func_annotations = NULL;
213
46.4k
    op->func_annotate = NULL;
214
46.4k
    op->func_typeparams = NULL;
215
46.4k
    op->vectorcall = _PyFunction_Vectorcall;
216
46.4k
    op->func_version = FUNC_VERSION_UNSET;
217
46.4k
    if (((code_obj->co_flags & CO_NESTED) == 0) ||
218
46.4k
        (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
22.1k
        _PyObject_SetDeferredRefcount((PyObject *)op);
226
22.1k
    }
227
46.4k
    _PyObject_GC_TRACK(op);
228
46.4k
    handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
229
46.4k
    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
46.4k
}
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
156k
{
304
156k
    return interp->func_state.func_version_cache +
305
156k
           (version % FUNC_VERSION_CACHE_SIZE);
306
156k
}
307
#endif
308
309
void
310
_PyFunction_SetVersion(PyFunctionObject *func, uint32_t version)
311
46.4k
{
312
46.4k
    assert(func->func_version == FUNC_VERSION_UNSET);
313
46.4k
    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
46.4k
    func->func_version = version;
317
46.4k
#ifndef Py_GIL_DISABLED
318
46.4k
    PyInterpreterState *interp = _PyInterpreterState_GET();
319
46.4k
    struct _func_version_cache_item *slot = get_cache_item(interp, version);
320
46.4k
    slot->func = func;
321
46.4k
    slot->code = func->func_code;
322
46.4k
#endif
323
46.4k
}
324
325
static void
326
func_clear_version(PyInterpreterState *interp, PyFunctionObject *func)
327
28.8k
{
328
28.8k
    if (func->func_version < FUNC_VERSION_FIRST_VALID) {
329
        // Version was never set or has already been cleared.
330
938
        return;
331
938
    }
332
27.9k
#ifndef Py_GIL_DISABLED
333
27.9k
    struct _func_version_cache_item *slot =
334
27.9k
        get_cache_item(interp, func->func_version);
335
27.9k
    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
27.9k
#endif
340
27.9k
    func->func_version = FUNC_VERSION_CLEARED;
341
27.9k
}
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
82.6k
{
360
82.6k
#ifndef Py_GIL_DISABLED
361
82.6k
    PyInterpreterState *interp = _PyInterpreterState_GET();
362
82.6k
    struct _func_version_cache_item *slot = get_cache_item(interp, version);
363
82.6k
    if (slot->code) {
364
28.8k
        assert(PyCode_Check(slot->code));
365
28.8k
        PyCodeObject *code = (PyCodeObject *)slot->code;
366
28.8k
        if (code->co_version == version) {
367
4.12k
            slot->code = NULL;
368
4.12k
            slot->func = NULL;
369
4.12k
        }
370
28.8k
    }
371
82.6k
#endif
372
82.6k
}
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
12.5k
{
403
12.5k
    return func->func_version;
404
12.5k
}
405
406
PyObject *
407
PyFunction_New(PyObject *code, PyObject *globals)
408
46.4k
{
409
46.4k
    return PyFunction_NewWithQualName(code, globals, NULL);
410
46.4k
}
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,
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
0
        Py_XSETREF(op->func_annotations, ann_dict);
570
0
        return ann_dict;
571
0
    }
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
44
{
653
44
    PyFunctionObject *op = _PyFunction_CAST(self);
654
44
    if (PySys_Audit("object.__getattr__", "Os", op, "__code__") < 0) {
655
0
        return NULL;
656
0
    }
657
658
44
    return Py_NewRef(op->func_code);
659
44
}
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
1.76k
{
713
1.76k
    PyFunctionObject *op = _PyFunction_CAST(self);
714
1.76k
    return Py_NewRef(op->func_name);
715
1.76k
}
716
717
static int
718
func_set_name(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
719
268
{
720
268
    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
268
    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
268
    Py_XSETREF(op->func_name, Py_NewRef(value));
729
268
    return 0;
730
268
}
731
732
static PyObject *
733
func_get_qualname(PyObject *self, void *Py_UNUSED(ignored))
734
1.67k
{
735
1.67k
    PyFunctionObject *op = _PyFunction_CAST(self);
736
1.67k
    return Py_NewRef(op->func_qualname);
737
1.67k
}
738
739
static int
740
func_set_qualname(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
741
343
{
742
343
    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
343
    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
343
    Py_XSETREF(op->func_qualname, Py_NewRef(value));
751
343
    return 0;
752
343
}
753
754
static PyObject *
755
func_get_defaults(PyObject *self, void *Py_UNUSED(ignored))
756
0
{
757
0
    PyFunctionObject *op = _PyFunction_CAST(self);
758
0
    if (PySys_Audit("object.__getattr__", "Os", op, "__defaults__") < 0) {
759
0
        return NULL;
760
0
    }
761
0
    if (op->func_defaults == NULL) {
762
0
        Py_RETURN_NONE;
763
0
    }
764
0
    return Py_NewRef(op->func_defaults);
765
0
}
766
767
static int
768
func_set_defaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
769
0
{
770
    /* Legal to del f.func_defaults.
771
     * Can only set func_defaults to NULL or a tuple. */
772
0
    PyFunctionObject *op = _PyFunction_CAST(self);
773
0
    if (value == Py_None)
774
0
        value = NULL;
775
0
    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
0
    if (value) {
781
0
        if (PySys_Audit("object.__setattr__", "OsO",
782
0
                        op, "__defaults__", value) < 0) {
783
0
            return -1;
784
0
        }
785
0
    } else if (PySys_Audit("object.__delattr__", "Os",
786
0
                           op, "__defaults__") < 0) {
787
0
        return -1;
788
0
    }
789
790
0
    handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS, op, value);
791
0
    _PyFunction_ClearVersion(op);
792
0
    Py_XSETREF(op->func_defaults, Py_XNewRef(value));
793
0
    return 0;
794
0
}
795
796
static PyObject *
797
func_get_kwdefaults(PyObject *self, void *Py_UNUSED(ignored))
798
0
{
799
0
    PyFunctionObject *op = _PyFunction_CAST(self);
800
0
    if (PySys_Audit("object.__getattr__", "Os",
801
0
                    op, "__kwdefaults__") < 0) {
802
0
        return NULL;
803
0
    }
804
0
    if (op->func_kwdefaults == NULL) {
805
0
        Py_RETURN_NONE;
806
0
    }
807
0
    return Py_NewRef(op->func_kwdefaults);
808
0
}
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
38
{
851
38
    if (self->func_annotate == NULL) {
852
38
        Py_RETURN_NONE;
853
38
    }
854
0
    return Py_NewRef(self->func_annotate);
855
38
}
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
28
{
867
28
    if (value == NULL) {
868
0
        PyErr_SetString(PyExc_TypeError,
869
0
            "__annotate__ cannot be deleted");
870
0
        return -1;
871
0
    }
872
28
    if (Py_IsNone(value)) {
873
28
        Py_XSETREF(self->func_annotate, value);
874
28
        return 0;
875
28
    }
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
28
}
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
0
{
900
0
    PyObject *d = NULL;
901
0
    if (self->func_annotations == NULL &&
902
0
        (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
0
    d = func_get_annotation_dict(self);
908
0
    return Py_XNewRef(d);
909
0
}
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
38
{
948
38
    if (self->func_typeparams == NULL) {
949
38
        return PyTuple_New(0);
950
38
    }
951
952
0
    assert(PyTuple_Check(self->func_typeparams));
953
0
    return Py_NewRef(self->func_typeparams);
954
0
}
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
28
{
966
    /* Not legal to del f.__type_params__ or to set it to anything
967
     * other than a tuple object. */
968
28
    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
28
    Py_XSETREF(self->func_typeparams, Py_NewRef(value));
974
28
    return 0;
975
28
}
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
28.8k
{
1112
28.8k
    PyFunctionObject *op = _PyFunction_CAST(self);
1113
0
    func_clear_version(_PyInterpreterState_GET(), op);
1114
28.8k
    PyObject *globals = op->func_globals;
1115
28.8k
    op->func_globals = NULL;
1116
28.8k
    if (globals != NULL) {
1117
28.5k
        _Py_DECREF_DICT(globals);
1118
28.5k
    }
1119
28.8k
    PyObject *builtins = op->func_builtins;
1120
28.8k
    op->func_builtins = NULL;
1121
28.8k
    if (builtins != NULL) {
1122
28.5k
        _Py_DECREF_BUILTINS(builtins);
1123
28.5k
    }
1124
28.8k
    Py_CLEAR(op->func_module);
1125
28.8k
    Py_CLEAR(op->func_defaults);
1126
28.8k
    Py_CLEAR(op->func_kwdefaults);
1127
28.8k
    Py_CLEAR(op->func_doc);
1128
28.8k
    Py_CLEAR(op->func_dict);
1129
28.8k
    Py_CLEAR(op->func_closure);
1130
28.8k
    Py_CLEAR(op->func_annotations);
1131
28.8k
    Py_CLEAR(op->func_annotate);
1132
28.8k
    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
28.8k
    Py_SETREF(op->func_name, &_Py_STR(empty));
1139
28.8k
    Py_SETREF(op->func_qualname, &_Py_STR(empty));
1140
28.8k
    return 0;
1141
28.8k
}
1142
1143
static void
1144
func_dealloc(PyObject *self)
1145
28.5k
{
1146
28.5k
    PyFunctionObject *op = _PyFunction_CAST(self);
1147
0
    _PyObject_ResurrectStart(self);
1148
28.5k
    handle_func_event(PyFunction_EVENT_DESTROY, op, NULL);
1149
28.5k
    if (_PyObject_ResurrectEnd(self)) {
1150
0
        return;
1151
0
    }
1152
28.5k
    _PyObject_GC_UNTRACK(op);
1153
28.5k
    FT_CLEAR_WEAKREFS(self, op->func_weakreflist);
1154
28.5k
    (void)func_clear((PyObject*)op);
1155
    // These aren't cleared by func_clear().
1156
28.5k
    _Py_DECREF_CODE((PyCodeObject *)op->func_code);
1157
28.5k
    Py_DECREF(op->func_name);
1158
28.5k
    Py_DECREF(op->func_qualname);
1159
28.5k
    PyObject_GC_Del(op);
1160
28.5k
}
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
13.1M
{
1173
13.1M
    PyFunctionObject *f = _PyFunction_CAST(self);
1174
13.1M
    Py_VISIT(f->func_code);
1175
13.1M
    Py_VISIT(f->func_globals);
1176
13.1M
    Py_VISIT(f->func_builtins);
1177
13.1M
    Py_VISIT(f->func_module);
1178
13.1M
    Py_VISIT(f->func_defaults);
1179
13.1M
    Py_VISIT(f->func_kwdefaults);
1180
13.1M
    Py_VISIT(f->func_doc);
1181
13.1M
    Py_VISIT(f->func_name);
1182
13.1M
    Py_VISIT(f->func_dict);
1183
13.1M
    Py_VISIT(f->func_closure);
1184
13.1M
    Py_VISIT(f->func_annotations);
1185
13.1M
    Py_VISIT(f->func_annotate);
1186
13.1M
    Py_VISIT(f->func_typeparams);
1187
13.1M
    Py_VISIT(f->func_qualname);
1188
13.1M
    return 0;
1189
13.1M
}
1190
1191
/* Bind a function to an object */
1192
static PyObject *
1193
func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
1194
9.13M
{
1195
9.13M
    if (obj == Py_None || obj == NULL) {
1196
1.76k
        return Py_NewRef(func);
1197
1.76k
    }
1198
9.13M
    return PyMethod_New(func, obj);
1199
9.13M
}
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.53k
{
1306
5.53k
    PyObject *value;
1307
5.53k
    int res = PyObject_GetOptionalAttr(wrapped, name, &value);
1308
5.53k
    if (value != NULL) {
1309
5.53k
        res = PyObject_SetAttr(wrapper, name, value);
1310
5.53k
        Py_DECREF(value);
1311
5.53k
    }
1312
5.53k
    return res;
1313
5.53k
}
1314
1315
// Similar to functools.wraps(wrapper, wrapped)
1316
static int
1317
functools_wraps(PyObject *wrapper, PyObject *wrapped)
1318
1.38k
{
1319
1.38k
#define COPY_ATTR(ATTR) \
1320
5.53k
    do { \
1321
5.53k
        if (functools_copy_attr(wrapper, wrapped, &_Py_ID(ATTR)) < 0) { \
1322
0
            return -1; \
1323
0
        } \
1324
5.53k
    } while (0) \
1325
1.38k
1326
1.38k
    COPY_ATTR(__module__);
1327
1.38k
    COPY_ATTR(__name__);
1328
1.38k
    COPY_ATTR(__qualname__);
1329
1.38k
    COPY_ATTR(__doc__);
1330
1.38k
    return 0;
1331
1332
1.38k
#undef COPY_ATTR
1333
1.38k
}
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
530k
    (assert(PyObject_TypeCheck((cm), &PyClassMethod_Type)), \
1428
530k
     _Py_CAST(classmethod*, cm))
1429
1430
static void
1431
cm_dealloc(PyObject *self)
1432
18
{
1433
18
    classmethod *cm = _PyClassMethod_CAST(self);
1434
18
    _PyObject_GC_UNTRACK((PyObject *)cm);
1435
18
    Py_XDECREF(cm->cm_callable);
1436
18
    Py_XDECREF(cm->cm_dict);
1437
18
    Py_TYPE(cm)->tp_free((PyObject *)cm);
1438
18
}
1439
1440
static int
1441
cm_traverse(PyObject *self, visitproc visit, void *arg)
1442
530k
{
1443
530k
    classmethod *cm = _PyClassMethod_CAST(self);
1444
530k
    Py_VISIT(cm->cm_callable);
1445
530k
    Py_VISIT(cm->cm_dict);
1446
530k
    return 0;
1447
530k
}
1448
1449
static int
1450
cm_clear(PyObject *self)
1451
12
{
1452
12
    classmethod *cm = _PyClassMethod_CAST(self);
1453
12
    Py_CLEAR(cm->cm_callable);
1454
12
    Py_CLEAR(cm->cm_dict);
1455
12
    return 0;
1456
12
}
1457
1458
1459
static PyObject *
1460
cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
1461
8.10k
{
1462
8.10k
    classmethod *cm = (classmethod *)self;
1463
1464
8.10k
    if (cm->cm_callable == NULL) {
1465
0
        PyErr_SetString(PyExc_RuntimeError,
1466
0
                        "uninitialized classmethod object");
1467
0
        return NULL;
1468
0
    }
1469
8.10k
    if (type == NULL)
1470
0
        type = (PyObject *)(Py_TYPE(obj));
1471
8.10k
    return PyMethod_New(cm->cm_callable, type);
1472
8.10k
}
1473
1474
static int
1475
cm_init(PyObject *self, PyObject *args, PyObject *kwds)
1476
1.13k
{
1477
1.13k
    classmethod *cm = (classmethod *)self;
1478
1.13k
    PyObject *callable;
1479
1480
1.13k
    if (!_PyArg_NoKeywords("classmethod", kwds))
1481
0
        return -1;
1482
1.13k
    if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable))
1483
0
        return -1;
1484
1.13k
    Py_XSETREF(cm->cm_callable, Py_NewRef(callable));
1485
1486
1.13k
    if (functools_wraps((PyObject *)cm, cm->cm_callable) < 0) {
1487
0
        return -1;
1488
0
    }
1489
1.13k
    return 0;
1490
1.13k
}
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
606
{
1501
606
    classmethod *cm = _PyClassMethod_CAST(self);
1502
0
    int res = _PyObject_IsAbstract(cm->cm_callable);
1503
606
    if (res == -1) {
1504
0
        return NULL;
1505
0
    }
1506
606
    else if (res) {
1507
0
        Py_RETURN_TRUE;
1508
0
    }
1509
606
    Py_RETURN_FALSE;
1510
606
}
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
7
{
1627
7
    classmethod *cm = (classmethod *)
1628
7
        PyType_GenericAlloc(&PyClassMethod_Type, 0);
1629
7
    if (cm != NULL) {
1630
7
        cm->cm_callable = Py_NewRef(callable);
1631
7
    }
1632
7
    return (PyObject *)cm;
1633
7
}
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
241k
    (assert(PyObject_TypeCheck((cm), &PyStaticMethod_Type)), \
1662
241k
     _Py_CAST(staticmethod*, cm))
1663
1664
static void
1665
sm_dealloc(PyObject *self)
1666
25
{
1667
25
    staticmethod *sm = _PyStaticMethod_CAST(self);
1668
25
    _PyObject_GC_UNTRACK((PyObject *)sm);
1669
25
    Py_XDECREF(sm->sm_callable);
1670
25
    Py_XDECREF(sm->sm_dict);
1671
25
    Py_TYPE(sm)->tp_free((PyObject *)sm);
1672
25
}
1673
1674
static int
1675
sm_traverse(PyObject *self, visitproc visit, void *arg)
1676
241k
{
1677
241k
    staticmethod *sm = _PyStaticMethod_CAST(self);
1678
241k
    Py_VISIT(sm->sm_callable);
1679
241k
    Py_VISIT(sm->sm_dict);
1680
241k
    return 0;
1681
241k
}
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
9.07k
{
1695
9.07k
    staticmethod *sm = (staticmethod *)self;
1696
1697
9.07k
    if (sm->sm_callable == NULL) {
1698
0
        PyErr_SetString(PyExc_RuntimeError,
1699
0
                        "uninitialized staticmethod object");
1700
0
        return NULL;
1701
0
    }
1702
9.07k
    return Py_NewRef(sm->sm_callable);
1703
9.07k
}
1704
1705
static int
1706
sm_init(PyObject *self, PyObject *args, PyObject *kwds)
1707
247
{
1708
247
    staticmethod *sm = (staticmethod *)self;
1709
247
    PyObject *callable;
1710
1711
247
    if (!_PyArg_NoKeywords("staticmethod", kwds))
1712
0
        return -1;
1713
247
    if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable))
1714
0
        return -1;
1715
247
    Py_XSETREF(sm->sm_callable, Py_NewRef(callable));
1716
1717
247
    if (functools_wraps((PyObject *)sm, sm->sm_callable) < 0) {
1718
0
        return -1;
1719
0
    }
1720
247
    return 0;
1721
247
}
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
0
{
1739
0
    staticmethod *sm = _PyStaticMethod_CAST(self);
1740
0
    int res = _PyObject_IsAbstract(sm->sm_callable);
1741
0
    if (res == -1) {
1742
0
        return NULL;
1743
0
    }
1744
0
    else if (res) {
1745
0
        Py_RETURN_TRUE;
1746
0
    }
1747
0
    Py_RETURN_FALSE;
1748
0
}
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
234
{
1862
234
    staticmethod *sm = (staticmethod *)
1863
234
        PyType_GenericAlloc(&PyStaticMethod_Type, 0);
1864
234
    if (sm != NULL) {
1865
234
        sm->sm_callable = Py_NewRef(callable);
1866
234
    }
1867
234
    return (PyObject *)sm;
1868
234
}