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