funcobject.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  1. /* Function object implementation */
  2. #include "Python.h"
  3. #include "pycore_ceval.h" // _PyEval_BuiltinsFromGlobals()
  4. #include "pycore_code.h" // _Py_next_func_version
  5. #include "pycore_object.h" // _PyObject_GC_UNTRACK()
  6. #include "pycore_pyerrors.h" // _PyErr_Occurred()
  7. #include "structmember.h" // PyMemberDef
  8. static PyObject* func_repr(PyFunctionObject *op);
  9. static const char *
  10. func_event_name(PyFunction_WatchEvent event) {
  11. switch (event) {
  12. #define CASE(op) \
  13. case PyFunction_EVENT_##op: \
  14. return "PyFunction_EVENT_" #op;
  15. PY_FOREACH_FUNC_EVENT(CASE)
  16. #undef CASE
  17. }
  18. Py_UNREACHABLE();
  19. }
  20. static void
  21. notify_func_watchers(PyInterpreterState *interp, PyFunction_WatchEvent event,
  22. PyFunctionObject *func, PyObject *new_value)
  23. {
  24. uint8_t bits = interp->active_func_watchers;
  25. int i = 0;
  26. while (bits) {
  27. assert(i < FUNC_MAX_WATCHERS);
  28. if (bits & 1) {
  29. PyFunction_WatchCallback cb = interp->func_watchers[i];
  30. // callback must be non-null if the watcher bit is set
  31. assert(cb != NULL);
  32. if (cb(event, func, new_value) < 0) {
  33. // Don't risk resurrecting the func if an unraisablehook keeps a
  34. // reference; pass a string as context.
  35. PyObject *context = NULL;
  36. PyObject *repr = func_repr(func);
  37. if (repr != NULL) {
  38. context = PyUnicode_FromFormat(
  39. "%s watcher callback for %U",
  40. func_event_name(event), repr);
  41. Py_DECREF(repr);
  42. }
  43. if (context == NULL) {
  44. context = Py_NewRef(Py_None);
  45. }
  46. PyErr_WriteUnraisable(context);
  47. Py_DECREF(context);
  48. }
  49. }
  50. i++;
  51. bits >>= 1;
  52. }
  53. }
  54. static inline void
  55. handle_func_event(PyFunction_WatchEvent event, PyFunctionObject *func,
  56. PyObject *new_value)
  57. {
  58. assert(Py_REFCNT(func) > 0);
  59. PyInterpreterState *interp = _PyInterpreterState_GET();
  60. assert(interp->_initialized);
  61. if (interp->active_func_watchers) {
  62. notify_func_watchers(interp, event, func, new_value);
  63. }
  64. }
  65. int
  66. PyFunction_AddWatcher(PyFunction_WatchCallback callback)
  67. {
  68. PyInterpreterState *interp = _PyInterpreterState_GET();
  69. assert(interp->_initialized);
  70. for (int i = 0; i < FUNC_MAX_WATCHERS; i++) {
  71. if (interp->func_watchers[i] == NULL) {
  72. interp->func_watchers[i] = callback;
  73. interp->active_func_watchers |= (1 << i);
  74. return i;
  75. }
  76. }
  77. PyErr_SetString(PyExc_RuntimeError, "no more func watcher IDs available");
  78. return -1;
  79. }
  80. int
  81. PyFunction_ClearWatcher(int watcher_id)
  82. {
  83. PyInterpreterState *interp = _PyInterpreterState_GET();
  84. if (watcher_id < 0 || watcher_id >= FUNC_MAX_WATCHERS) {
  85. PyErr_Format(PyExc_ValueError, "invalid func watcher ID %d",
  86. watcher_id);
  87. return -1;
  88. }
  89. if (!interp->func_watchers[watcher_id]) {
  90. PyErr_Format(PyExc_ValueError, "no func watcher set for ID %d",
  91. watcher_id);
  92. return -1;
  93. }
  94. interp->func_watchers[watcher_id] = NULL;
  95. interp->active_func_watchers &= ~(1 << watcher_id);
  96. return 0;
  97. }
  98. PyFunctionObject *
  99. _PyFunction_FromConstructor(PyFrameConstructor *constr)
  100. {
  101. PyObject *module = Py_XNewRef(PyDict_GetItemWithError(constr->fc_globals, &_Py_ID(__name__)));
  102. if (!module && PyErr_Occurred()) {
  103. return NULL;
  104. }
  105. PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
  106. if (op == NULL) {
  107. Py_XDECREF(module);
  108. return NULL;
  109. }
  110. op->func_globals = Py_NewRef(constr->fc_globals);
  111. op->func_builtins = Py_NewRef(constr->fc_builtins);
  112. op->func_name = Py_NewRef(constr->fc_name);
  113. op->func_qualname = Py_NewRef(constr->fc_qualname);
  114. op->func_code = Py_NewRef(constr->fc_code);
  115. op->func_defaults = Py_XNewRef(constr->fc_defaults);
  116. op->func_kwdefaults = Py_XNewRef(constr->fc_kwdefaults);
  117. op->func_closure = Py_XNewRef(constr->fc_closure);
  118. op->func_doc = Py_NewRef(Py_None);
  119. op->func_dict = NULL;
  120. op->func_weakreflist = NULL;
  121. op->func_module = module;
  122. op->func_annotations = NULL;
  123. op->func_typeparams = NULL;
  124. op->vectorcall = _PyFunction_Vectorcall;
  125. op->func_version = 0;
  126. _PyObject_GC_TRACK(op);
  127. handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
  128. return op;
  129. }
  130. PyObject *
  131. PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
  132. {
  133. assert(globals != NULL);
  134. assert(PyDict_Check(globals));
  135. Py_INCREF(globals);
  136. PyThreadState *tstate = _PyThreadState_GET();
  137. PyCodeObject *code_obj = (PyCodeObject *)Py_NewRef(code);
  138. assert(code_obj->co_name != NULL);
  139. PyObject *name = Py_NewRef(code_obj->co_name);
  140. if (!qualname) {
  141. qualname = code_obj->co_qualname;
  142. }
  143. assert(qualname != NULL);
  144. Py_INCREF(qualname);
  145. PyObject *consts = code_obj->co_consts;
  146. assert(PyTuple_Check(consts));
  147. PyObject *doc;
  148. if (PyTuple_Size(consts) >= 1) {
  149. doc = PyTuple_GetItem(consts, 0);
  150. if (!PyUnicode_Check(doc)) {
  151. doc = Py_None;
  152. }
  153. }
  154. else {
  155. doc = Py_None;
  156. }
  157. Py_INCREF(doc);
  158. // __module__: Use globals['__name__'] if it exists, or NULL.
  159. PyObject *module = PyDict_GetItemWithError(globals, &_Py_ID(__name__));
  160. PyObject *builtins = NULL;
  161. if (module == NULL && _PyErr_Occurred(tstate)) {
  162. goto error;
  163. }
  164. Py_XINCREF(module);
  165. builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
  166. if (builtins == NULL) {
  167. goto error;
  168. }
  169. Py_INCREF(builtins);
  170. PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
  171. if (op == NULL) {
  172. goto error;
  173. }
  174. /* Note: No failures from this point on, since func_dealloc() does not
  175. expect a partially-created object. */
  176. op->func_globals = globals;
  177. op->func_builtins = builtins;
  178. op->func_name = name;
  179. op->func_qualname = qualname;
  180. op->func_code = (PyObject*)code_obj;
  181. op->func_defaults = NULL; // No default positional arguments
  182. op->func_kwdefaults = NULL; // No default keyword arguments
  183. op->func_closure = NULL;
  184. op->func_doc = doc;
  185. op->func_dict = NULL;
  186. op->func_weakreflist = NULL;
  187. op->func_module = module;
  188. op->func_annotations = NULL;
  189. op->func_typeparams = NULL;
  190. op->vectorcall = _PyFunction_Vectorcall;
  191. op->func_version = 0;
  192. _PyObject_GC_TRACK(op);
  193. handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
  194. return (PyObject *)op;
  195. error:
  196. Py_DECREF(globals);
  197. Py_DECREF(code_obj);
  198. Py_DECREF(name);
  199. Py_DECREF(qualname);
  200. Py_DECREF(doc);
  201. Py_XDECREF(module);
  202. Py_XDECREF(builtins);
  203. return NULL;
  204. }
  205. uint32_t _PyFunction_GetVersionForCurrentState(PyFunctionObject *func)
  206. {
  207. if (func->func_version != 0) {
  208. return func->func_version;
  209. }
  210. if (func->vectorcall != _PyFunction_Vectorcall) {
  211. return 0;
  212. }
  213. PyInterpreterState *interp = _PyInterpreterState_GET();
  214. if (interp->func_state.next_version == 0) {
  215. return 0;
  216. }
  217. uint32_t v = interp->func_state.next_version++;
  218. func->func_version = v;
  219. return v;
  220. }
  221. PyObject *
  222. PyFunction_New(PyObject *code, PyObject *globals)
  223. {
  224. return PyFunction_NewWithQualName(code, globals, NULL);
  225. }
  226. PyObject *
  227. PyFunction_GetCode(PyObject *op)
  228. {
  229. if (!PyFunction_Check(op)) {
  230. PyErr_BadInternalCall();
  231. return NULL;
  232. }
  233. return ((PyFunctionObject *) op) -> func_code;
  234. }
  235. PyObject *
  236. PyFunction_GetGlobals(PyObject *op)
  237. {
  238. if (!PyFunction_Check(op)) {
  239. PyErr_BadInternalCall();
  240. return NULL;
  241. }
  242. return ((PyFunctionObject *) op) -> func_globals;
  243. }
  244. PyObject *
  245. PyFunction_GetModule(PyObject *op)
  246. {
  247. if (!PyFunction_Check(op)) {
  248. PyErr_BadInternalCall();
  249. return NULL;
  250. }
  251. return ((PyFunctionObject *) op) -> func_module;
  252. }
  253. PyObject *
  254. PyFunction_GetDefaults(PyObject *op)
  255. {
  256. if (!PyFunction_Check(op)) {
  257. PyErr_BadInternalCall();
  258. return NULL;
  259. }
  260. return ((PyFunctionObject *) op) -> func_defaults;
  261. }
  262. int
  263. PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
  264. {
  265. if (!PyFunction_Check(op)) {
  266. PyErr_BadInternalCall();
  267. return -1;
  268. }
  269. if (defaults == Py_None)
  270. defaults = NULL;
  271. else if (defaults && PyTuple_Check(defaults)) {
  272. Py_INCREF(defaults);
  273. }
  274. else {
  275. PyErr_SetString(PyExc_SystemError, "non-tuple default args");
  276. return -1;
  277. }
  278. handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS,
  279. (PyFunctionObject *) op, defaults);
  280. ((PyFunctionObject *)op)->func_version = 0;
  281. Py_XSETREF(((PyFunctionObject *)op)->func_defaults, defaults);
  282. return 0;
  283. }
  284. void
  285. PyFunction_SetVectorcall(PyFunctionObject *func, vectorcallfunc vectorcall)
  286. {
  287. assert(func != NULL);
  288. func->func_version = 0;
  289. func->vectorcall = vectorcall;
  290. }
  291. PyObject *
  292. PyFunction_GetKwDefaults(PyObject *op)
  293. {
  294. if (!PyFunction_Check(op)) {
  295. PyErr_BadInternalCall();
  296. return NULL;
  297. }
  298. return ((PyFunctionObject *) op) -> func_kwdefaults;
  299. }
  300. int
  301. PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults)
  302. {
  303. if (!PyFunction_Check(op)) {
  304. PyErr_BadInternalCall();
  305. return -1;
  306. }
  307. if (defaults == Py_None)
  308. defaults = NULL;
  309. else if (defaults && PyDict_Check(defaults)) {
  310. Py_INCREF(defaults);
  311. }
  312. else {
  313. PyErr_SetString(PyExc_SystemError,
  314. "non-dict keyword only default args");
  315. return -1;
  316. }
  317. handle_func_event(PyFunction_EVENT_MODIFY_KWDEFAULTS,
  318. (PyFunctionObject *) op, defaults);
  319. ((PyFunctionObject *)op)->func_version = 0;
  320. Py_XSETREF(((PyFunctionObject *)op)->func_kwdefaults, defaults);
  321. return 0;
  322. }
  323. PyObject *
  324. PyFunction_GetClosure(PyObject *op)
  325. {
  326. if (!PyFunction_Check(op)) {
  327. PyErr_BadInternalCall();
  328. return NULL;
  329. }
  330. return ((PyFunctionObject *) op) -> func_closure;
  331. }
  332. int
  333. PyFunction_SetClosure(PyObject *op, PyObject *closure)
  334. {
  335. if (!PyFunction_Check(op)) {
  336. PyErr_BadInternalCall();
  337. return -1;
  338. }
  339. if (closure == Py_None)
  340. closure = NULL;
  341. else if (PyTuple_Check(closure)) {
  342. Py_INCREF(closure);
  343. }
  344. else {
  345. PyErr_Format(PyExc_SystemError,
  346. "expected tuple for closure, got '%.100s'",
  347. Py_TYPE(closure)->tp_name);
  348. return -1;
  349. }
  350. ((PyFunctionObject *)op)->func_version = 0;
  351. Py_XSETREF(((PyFunctionObject *)op)->func_closure, closure);
  352. return 0;
  353. }
  354. static PyObject *
  355. func_get_annotation_dict(PyFunctionObject *op)
  356. {
  357. if (op->func_annotations == NULL) {
  358. return NULL;
  359. }
  360. if (PyTuple_CheckExact(op->func_annotations)) {
  361. PyObject *ann_tuple = op->func_annotations;
  362. PyObject *ann_dict = PyDict_New();
  363. if (ann_dict == NULL) {
  364. return NULL;
  365. }
  366. assert(PyTuple_GET_SIZE(ann_tuple) % 2 == 0);
  367. for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(ann_tuple); i += 2) {
  368. int err = PyDict_SetItem(ann_dict,
  369. PyTuple_GET_ITEM(ann_tuple, i),
  370. PyTuple_GET_ITEM(ann_tuple, i + 1));
  371. if (err < 0) {
  372. return NULL;
  373. }
  374. }
  375. Py_SETREF(op->func_annotations, ann_dict);
  376. }
  377. assert(PyDict_Check(op->func_annotations));
  378. return op->func_annotations;
  379. }
  380. PyObject *
  381. PyFunction_GetAnnotations(PyObject *op)
  382. {
  383. if (!PyFunction_Check(op)) {
  384. PyErr_BadInternalCall();
  385. return NULL;
  386. }
  387. return func_get_annotation_dict((PyFunctionObject *)op);
  388. }
  389. int
  390. PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)
  391. {
  392. if (!PyFunction_Check(op)) {
  393. PyErr_BadInternalCall();
  394. return -1;
  395. }
  396. if (annotations == Py_None)
  397. annotations = NULL;
  398. else if (annotations && PyDict_Check(annotations)) {
  399. Py_INCREF(annotations);
  400. }
  401. else {
  402. PyErr_SetString(PyExc_SystemError,
  403. "non-dict annotations");
  404. return -1;
  405. }
  406. ((PyFunctionObject *)op)->func_version = 0;
  407. Py_XSETREF(((PyFunctionObject *)op)->func_annotations, annotations);
  408. return 0;
  409. }
  410. /* Methods */
  411. #define OFF(x) offsetof(PyFunctionObject, x)
  412. static PyMemberDef func_memberlist[] = {
  413. {"__closure__", T_OBJECT, OFF(func_closure), READONLY},
  414. {"__doc__", T_OBJECT, OFF(func_doc), 0},
  415. {"__globals__", T_OBJECT, OFF(func_globals), READONLY},
  416. {"__module__", T_OBJECT, OFF(func_module), 0},
  417. {"__builtins__", T_OBJECT, OFF(func_builtins), READONLY},
  418. {NULL} /* Sentinel */
  419. };
  420. static PyObject *
  421. func_get_code(PyFunctionObject *op, void *Py_UNUSED(ignored))
  422. {
  423. if (PySys_Audit("object.__getattr__", "Os", op, "__code__") < 0) {
  424. return NULL;
  425. }
  426. return Py_NewRef(op->func_code);
  427. }
  428. static int
  429. func_set_code(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
  430. {
  431. Py_ssize_t nclosure;
  432. int nfree;
  433. /* Not legal to del f.func_code or to set it to anything
  434. * other than a code object. */
  435. if (value == NULL || !PyCode_Check(value)) {
  436. PyErr_SetString(PyExc_TypeError,
  437. "__code__ must be set to a code object");
  438. return -1;
  439. }
  440. if (PySys_Audit("object.__setattr__", "OsO",
  441. op, "__code__", value) < 0) {
  442. return -1;
  443. }
  444. nfree = ((PyCodeObject *)value)->co_nfreevars;
  445. nclosure = (op->func_closure == NULL ? 0 :
  446. PyTuple_GET_SIZE(op->func_closure));
  447. if (nclosure != nfree) {
  448. PyErr_Format(PyExc_ValueError,
  449. "%U() requires a code object with %zd free vars,"
  450. " not %zd",
  451. op->func_name,
  452. nclosure, nfree);
  453. return -1;
  454. }
  455. handle_func_event(PyFunction_EVENT_MODIFY_CODE, op, value);
  456. op->func_version = 0;
  457. Py_XSETREF(op->func_code, Py_NewRef(value));
  458. return 0;
  459. }
  460. static PyObject *
  461. func_get_name(PyFunctionObject *op, void *Py_UNUSED(ignored))
  462. {
  463. return Py_NewRef(op->func_name);
  464. }
  465. static int
  466. func_set_name(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
  467. {
  468. /* Not legal to del f.func_name or to set it to anything
  469. * other than a string object. */
  470. if (value == NULL || !PyUnicode_Check(value)) {
  471. PyErr_SetString(PyExc_TypeError,
  472. "__name__ must be set to a string object");
  473. return -1;
  474. }
  475. Py_XSETREF(op->func_name, Py_NewRef(value));
  476. return 0;
  477. }
  478. static PyObject *
  479. func_get_qualname(PyFunctionObject *op, void *Py_UNUSED(ignored))
  480. {
  481. return Py_NewRef(op->func_qualname);
  482. }
  483. static int
  484. func_set_qualname(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
  485. {
  486. /* Not legal to del f.__qualname__ or to set it to anything
  487. * other than a string object. */
  488. if (value == NULL || !PyUnicode_Check(value)) {
  489. PyErr_SetString(PyExc_TypeError,
  490. "__qualname__ must be set to a string object");
  491. return -1;
  492. }
  493. Py_XSETREF(op->func_qualname, Py_NewRef(value));
  494. return 0;
  495. }
  496. static PyObject *
  497. func_get_defaults(PyFunctionObject *op, void *Py_UNUSED(ignored))
  498. {
  499. if (PySys_Audit("object.__getattr__", "Os", op, "__defaults__") < 0) {
  500. return NULL;
  501. }
  502. if (op->func_defaults == NULL) {
  503. Py_RETURN_NONE;
  504. }
  505. return Py_NewRef(op->func_defaults);
  506. }
  507. static int
  508. func_set_defaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
  509. {
  510. /* Legal to del f.func_defaults.
  511. * Can only set func_defaults to NULL or a tuple. */
  512. if (value == Py_None)
  513. value = NULL;
  514. if (value != NULL && !PyTuple_Check(value)) {
  515. PyErr_SetString(PyExc_TypeError,
  516. "__defaults__ must be set to a tuple object");
  517. return -1;
  518. }
  519. if (value) {
  520. if (PySys_Audit("object.__setattr__", "OsO",
  521. op, "__defaults__", value) < 0) {
  522. return -1;
  523. }
  524. } else if (PySys_Audit("object.__delattr__", "Os",
  525. op, "__defaults__") < 0) {
  526. return -1;
  527. }
  528. handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS, op, value);
  529. op->func_version = 0;
  530. Py_XSETREF(op->func_defaults, Py_XNewRef(value));
  531. return 0;
  532. }
  533. static PyObject *
  534. func_get_kwdefaults(PyFunctionObject *op, void *Py_UNUSED(ignored))
  535. {
  536. if (PySys_Audit("object.__getattr__", "Os",
  537. op, "__kwdefaults__") < 0) {
  538. return NULL;
  539. }
  540. if (op->func_kwdefaults == NULL) {
  541. Py_RETURN_NONE;
  542. }
  543. return Py_NewRef(op->func_kwdefaults);
  544. }
  545. static int
  546. func_set_kwdefaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
  547. {
  548. if (value == Py_None)
  549. value = NULL;
  550. /* Legal to del f.func_kwdefaults.
  551. * Can only set func_kwdefaults to NULL or a dict. */
  552. if (value != NULL && !PyDict_Check(value)) {
  553. PyErr_SetString(PyExc_TypeError,
  554. "__kwdefaults__ must be set to a dict object");
  555. return -1;
  556. }
  557. if (value) {
  558. if (PySys_Audit("object.__setattr__", "OsO",
  559. op, "__kwdefaults__", value) < 0) {
  560. return -1;
  561. }
  562. } else if (PySys_Audit("object.__delattr__", "Os",
  563. op, "__kwdefaults__") < 0) {
  564. return -1;
  565. }
  566. handle_func_event(PyFunction_EVENT_MODIFY_KWDEFAULTS, op, value);
  567. op->func_version = 0;
  568. Py_XSETREF(op->func_kwdefaults, Py_XNewRef(value));
  569. return 0;
  570. }
  571. static PyObject *
  572. func_get_annotations(PyFunctionObject *op, void *Py_UNUSED(ignored))
  573. {
  574. if (op->func_annotations == NULL) {
  575. op->func_annotations = PyDict_New();
  576. if (op->func_annotations == NULL)
  577. return NULL;
  578. }
  579. PyObject *d = func_get_annotation_dict(op);
  580. return Py_XNewRef(d);
  581. }
  582. static int
  583. func_set_annotations(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
  584. {
  585. if (value == Py_None)
  586. value = NULL;
  587. /* Legal to del f.func_annotations.
  588. * Can only set func_annotations to NULL (through C api)
  589. * or a dict. */
  590. if (value != NULL && !PyDict_Check(value)) {
  591. PyErr_SetString(PyExc_TypeError,
  592. "__annotations__ must be set to a dict object");
  593. return -1;
  594. }
  595. op->func_version = 0;
  596. Py_XSETREF(op->func_annotations, Py_XNewRef(value));
  597. return 0;
  598. }
  599. static PyObject *
  600. func_get_type_params(PyFunctionObject *op, void *Py_UNUSED(ignored))
  601. {
  602. if (op->func_typeparams == NULL) {
  603. return PyTuple_New(0);
  604. }
  605. assert(PyTuple_Check(op->func_typeparams));
  606. return Py_NewRef(op->func_typeparams);
  607. }
  608. static int
  609. func_set_type_params(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
  610. {
  611. /* Not legal to del f.__type_params__ or to set it to anything
  612. * other than a tuple object. */
  613. if (value == NULL || !PyTuple_Check(value)) {
  614. PyErr_SetString(PyExc_TypeError,
  615. "__type_params__ must be set to a tuple");
  616. return -1;
  617. }
  618. Py_XSETREF(op->func_typeparams, Py_NewRef(value));
  619. return 0;
  620. }
  621. PyObject *
  622. _Py_set_function_type_params(PyThreadState *Py_UNUSED(ignored), PyObject *func,
  623. PyObject *type_params)
  624. {
  625. assert(PyFunction_Check(func));
  626. assert(PyTuple_Check(type_params));
  627. PyFunctionObject *f = (PyFunctionObject *)func;
  628. Py_XSETREF(f->func_typeparams, Py_NewRef(type_params));
  629. return Py_NewRef(func);
  630. }
  631. static PyGetSetDef func_getsetlist[] = {
  632. {"__code__", (getter)func_get_code, (setter)func_set_code},
  633. {"__defaults__", (getter)func_get_defaults,
  634. (setter)func_set_defaults},
  635. {"__kwdefaults__", (getter)func_get_kwdefaults,
  636. (setter)func_set_kwdefaults},
  637. {"__annotations__", (getter)func_get_annotations,
  638. (setter)func_set_annotations},
  639. {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
  640. {"__name__", (getter)func_get_name, (setter)func_set_name},
  641. {"__qualname__", (getter)func_get_qualname, (setter)func_set_qualname},
  642. {"__type_params__", (getter)func_get_type_params,
  643. (setter)func_set_type_params},
  644. {NULL} /* Sentinel */
  645. };
  646. /*[clinic input]
  647. class function "PyFunctionObject *" "&PyFunction_Type"
  648. [clinic start generated code]*/
  649. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=70af9c90aa2e71b0]*/
  650. #include "clinic/funcobject.c.h"
  651. /* function.__new__() maintains the following invariants for closures.
  652. The closure must correspond to the free variables of the code object.
  653. if len(code.co_freevars) == 0:
  654. closure = NULL
  655. else:
  656. len(closure) == len(code.co_freevars)
  657. for every elt in closure, type(elt) == cell
  658. */
  659. /*[clinic input]
  660. @classmethod
  661. function.__new__ as func_new
  662. code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
  663. a code object
  664. globals: object(subclass_of="&PyDict_Type")
  665. the globals dictionary
  666. name: object = None
  667. a string that overrides the name from the code object
  668. argdefs as defaults: object = None
  669. a tuple that specifies the default argument values
  670. closure: object = None
  671. a tuple that supplies the bindings for free variables
  672. Create a function object.
  673. [clinic start generated code]*/
  674. static PyObject *
  675. func_new_impl(PyTypeObject *type, PyCodeObject *code, PyObject *globals,
  676. PyObject *name, PyObject *defaults, PyObject *closure)
  677. /*[clinic end generated code: output=99c6d9da3a24e3be input=93611752fc2daf11]*/
  678. {
  679. PyFunctionObject *newfunc;
  680. Py_ssize_t nclosure;
  681. if (name != Py_None && !PyUnicode_Check(name)) {
  682. PyErr_SetString(PyExc_TypeError,
  683. "arg 3 (name) must be None or string");
  684. return NULL;
  685. }
  686. if (defaults != Py_None && !PyTuple_Check(defaults)) {
  687. PyErr_SetString(PyExc_TypeError,
  688. "arg 4 (defaults) must be None or tuple");
  689. return NULL;
  690. }
  691. if (!PyTuple_Check(closure)) {
  692. if (code->co_nfreevars && closure == Py_None) {
  693. PyErr_SetString(PyExc_TypeError,
  694. "arg 5 (closure) must be tuple");
  695. return NULL;
  696. }
  697. else if (closure != Py_None) {
  698. PyErr_SetString(PyExc_TypeError,
  699. "arg 5 (closure) must be None or tuple");
  700. return NULL;
  701. }
  702. }
  703. /* check that the closure is well-formed */
  704. nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
  705. if (code->co_nfreevars != nclosure)
  706. return PyErr_Format(PyExc_ValueError,
  707. "%U requires closure of length %zd, not %zd",
  708. code->co_name, code->co_nfreevars, nclosure);
  709. if (nclosure) {
  710. Py_ssize_t i;
  711. for (i = 0; i < nclosure; i++) {
  712. PyObject *o = PyTuple_GET_ITEM(closure, i);
  713. if (!PyCell_Check(o)) {
  714. return PyErr_Format(PyExc_TypeError,
  715. "arg 5 (closure) expected cell, found %s",
  716. Py_TYPE(o)->tp_name);
  717. }
  718. }
  719. }
  720. if (PySys_Audit("function.__new__", "O", code) < 0) {
  721. return NULL;
  722. }
  723. newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
  724. globals);
  725. if (newfunc == NULL) {
  726. return NULL;
  727. }
  728. if (name != Py_None) {
  729. Py_SETREF(newfunc->func_name, Py_NewRef(name));
  730. }
  731. if (defaults != Py_None) {
  732. newfunc->func_defaults = Py_NewRef(defaults);
  733. }
  734. if (closure != Py_None) {
  735. newfunc->func_closure = Py_NewRef(closure);
  736. }
  737. return (PyObject *)newfunc;
  738. }
  739. static int
  740. func_clear(PyFunctionObject *op)
  741. {
  742. op->func_version = 0;
  743. Py_CLEAR(op->func_globals);
  744. Py_CLEAR(op->func_builtins);
  745. Py_CLEAR(op->func_module);
  746. Py_CLEAR(op->func_defaults);
  747. Py_CLEAR(op->func_kwdefaults);
  748. Py_CLEAR(op->func_doc);
  749. Py_CLEAR(op->func_dict);
  750. Py_CLEAR(op->func_closure);
  751. Py_CLEAR(op->func_annotations);
  752. Py_CLEAR(op->func_typeparams);
  753. // Don't Py_CLEAR(op->func_code), since code is always required
  754. // to be non-NULL. Similarly, name and qualname shouldn't be NULL.
  755. // However, name and qualname could be str subclasses, so they
  756. // could have reference cycles. The solution is to replace them
  757. // with a genuinely immutable string.
  758. Py_SETREF(op->func_name, Py_NewRef(&_Py_STR(empty)));
  759. Py_SETREF(op->func_qualname, Py_NewRef(&_Py_STR(empty)));
  760. return 0;
  761. }
  762. static void
  763. func_dealloc(PyFunctionObject *op)
  764. {
  765. assert(Py_REFCNT(op) == 0);
  766. Py_SET_REFCNT(op, 1);
  767. handle_func_event(PyFunction_EVENT_DESTROY, op, NULL);
  768. if (Py_REFCNT(op) > 1) {
  769. Py_SET_REFCNT(op, Py_REFCNT(op) - 1);
  770. return;
  771. }
  772. Py_SET_REFCNT(op, 0);
  773. _PyObject_GC_UNTRACK(op);
  774. if (op->func_weakreflist != NULL) {
  775. PyObject_ClearWeakRefs((PyObject *) op);
  776. }
  777. (void)func_clear(op);
  778. // These aren't cleared by func_clear().
  779. Py_DECREF(op->func_code);
  780. Py_DECREF(op->func_name);
  781. Py_DECREF(op->func_qualname);
  782. PyObject_GC_Del(op);
  783. }
  784. static PyObject*
  785. func_repr(PyFunctionObject *op)
  786. {
  787. return PyUnicode_FromFormat("<function %U at %p>",
  788. op->func_qualname, op);
  789. }
  790. static int
  791. func_traverse(PyFunctionObject *f, visitproc visit, void *arg)
  792. {
  793. Py_VISIT(f->func_code);
  794. Py_VISIT(f->func_globals);
  795. Py_VISIT(f->func_builtins);
  796. Py_VISIT(f->func_module);
  797. Py_VISIT(f->func_defaults);
  798. Py_VISIT(f->func_kwdefaults);
  799. Py_VISIT(f->func_doc);
  800. Py_VISIT(f->func_name);
  801. Py_VISIT(f->func_dict);
  802. Py_VISIT(f->func_closure);
  803. Py_VISIT(f->func_annotations);
  804. Py_VISIT(f->func_typeparams);
  805. Py_VISIT(f->func_qualname);
  806. return 0;
  807. }
  808. /* Bind a function to an object */
  809. static PyObject *
  810. func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
  811. {
  812. if (obj == Py_None || obj == NULL) {
  813. return Py_NewRef(func);
  814. }
  815. return PyMethod_New(func, obj);
  816. }
  817. PyTypeObject PyFunction_Type = {
  818. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  819. "function",
  820. sizeof(PyFunctionObject),
  821. 0,
  822. (destructor)func_dealloc, /* tp_dealloc */
  823. offsetof(PyFunctionObject, vectorcall), /* tp_vectorcall_offset */
  824. 0, /* tp_getattr */
  825. 0, /* tp_setattr */
  826. 0, /* tp_as_async */
  827. (reprfunc)func_repr, /* tp_repr */
  828. 0, /* tp_as_number */
  829. 0, /* tp_as_sequence */
  830. 0, /* tp_as_mapping */
  831. 0, /* tp_hash */
  832. PyVectorcall_Call, /* tp_call */
  833. 0, /* tp_str */
  834. 0, /* tp_getattro */
  835. 0, /* tp_setattro */
  836. 0, /* tp_as_buffer */
  837. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  838. Py_TPFLAGS_HAVE_VECTORCALL |
  839. Py_TPFLAGS_METHOD_DESCRIPTOR, /* tp_flags */
  840. func_new__doc__, /* tp_doc */
  841. (traverseproc)func_traverse, /* tp_traverse */
  842. (inquiry)func_clear, /* tp_clear */
  843. 0, /* tp_richcompare */
  844. offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
  845. 0, /* tp_iter */
  846. 0, /* tp_iternext */
  847. 0, /* tp_methods */
  848. func_memberlist, /* tp_members */
  849. func_getsetlist, /* tp_getset */
  850. 0, /* tp_base */
  851. 0, /* tp_dict */
  852. func_descr_get, /* tp_descr_get */
  853. 0, /* tp_descr_set */
  854. offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */
  855. 0, /* tp_init */
  856. 0, /* tp_alloc */
  857. func_new, /* tp_new */
  858. };
  859. static int
  860. functools_copy_attr(PyObject *wrapper, PyObject *wrapped, PyObject *name)
  861. {
  862. PyObject *value = PyObject_GetAttr(wrapped, name);
  863. if (value == NULL) {
  864. if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
  865. PyErr_Clear();
  866. return 0;
  867. }
  868. return -1;
  869. }
  870. int res = PyObject_SetAttr(wrapper, name, value);
  871. Py_DECREF(value);
  872. return res;
  873. }
  874. // Similar to functools.wraps(wrapper, wrapped)
  875. static int
  876. functools_wraps(PyObject *wrapper, PyObject *wrapped)
  877. {
  878. #define COPY_ATTR(ATTR) \
  879. do { \
  880. if (functools_copy_attr(wrapper, wrapped, &_Py_ID(ATTR)) < 0) { \
  881. return -1; \
  882. } \
  883. } while (0) \
  884. COPY_ATTR(__module__);
  885. COPY_ATTR(__name__);
  886. COPY_ATTR(__qualname__);
  887. COPY_ATTR(__doc__);
  888. COPY_ATTR(__annotations__);
  889. return 0;
  890. #undef COPY_ATTR
  891. }
  892. /* Class method object */
  893. /* A class method receives the class as implicit first argument,
  894. just like an instance method receives the instance.
  895. To declare a class method, use this idiom:
  896. class C:
  897. @classmethod
  898. def f(cls, arg1, arg2, argN):
  899. ...
  900. It can be called either on the class (e.g. C.f()) or on an instance
  901. (e.g. C().f()); the instance is ignored except for its class.
  902. If a class method is called for a derived class, the derived class
  903. object is passed as the implied first argument.
  904. Class methods are different than C++ or Java static methods.
  905. If you want those, see static methods below.
  906. */
  907. typedef struct {
  908. PyObject_HEAD
  909. PyObject *cm_callable;
  910. PyObject *cm_dict;
  911. } classmethod;
  912. static void
  913. cm_dealloc(classmethod *cm)
  914. {
  915. _PyObject_GC_UNTRACK((PyObject *)cm);
  916. Py_XDECREF(cm->cm_callable);
  917. Py_XDECREF(cm->cm_dict);
  918. Py_TYPE(cm)->tp_free((PyObject *)cm);
  919. }
  920. static int
  921. cm_traverse(classmethod *cm, visitproc visit, void *arg)
  922. {
  923. Py_VISIT(cm->cm_callable);
  924. Py_VISIT(cm->cm_dict);
  925. return 0;
  926. }
  927. static int
  928. cm_clear(classmethod *cm)
  929. {
  930. Py_CLEAR(cm->cm_callable);
  931. Py_CLEAR(cm->cm_dict);
  932. return 0;
  933. }
  934. static PyObject *
  935. cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
  936. {
  937. classmethod *cm = (classmethod *)self;
  938. if (cm->cm_callable == NULL) {
  939. PyErr_SetString(PyExc_RuntimeError,
  940. "uninitialized classmethod object");
  941. return NULL;
  942. }
  943. if (type == NULL)
  944. type = (PyObject *)(Py_TYPE(obj));
  945. if (Py_TYPE(cm->cm_callable)->tp_descr_get != NULL) {
  946. return Py_TYPE(cm->cm_callable)->tp_descr_get(cm->cm_callable, type,
  947. type);
  948. }
  949. return PyMethod_New(cm->cm_callable, type);
  950. }
  951. static int
  952. cm_init(PyObject *self, PyObject *args, PyObject *kwds)
  953. {
  954. classmethod *cm = (classmethod *)self;
  955. PyObject *callable;
  956. if (!_PyArg_NoKeywords("classmethod", kwds))
  957. return -1;
  958. if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable))
  959. return -1;
  960. Py_XSETREF(cm->cm_callable, Py_NewRef(callable));
  961. if (functools_wraps((PyObject *)cm, cm->cm_callable) < 0) {
  962. return -1;
  963. }
  964. return 0;
  965. }
  966. static PyMemberDef cm_memberlist[] = {
  967. {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY},
  968. {"__wrapped__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY},
  969. {NULL} /* Sentinel */
  970. };
  971. static PyObject *
  972. cm_get___isabstractmethod__(classmethod *cm, void *closure)
  973. {
  974. int res = _PyObject_IsAbstract(cm->cm_callable);
  975. if (res == -1) {
  976. return NULL;
  977. }
  978. else if (res) {
  979. Py_RETURN_TRUE;
  980. }
  981. Py_RETURN_FALSE;
  982. }
  983. static PyGetSetDef cm_getsetlist[] = {
  984. {"__isabstractmethod__",
  985. (getter)cm_get___isabstractmethod__, NULL, NULL, NULL},
  986. {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
  987. {NULL} /* Sentinel */
  988. };
  989. static PyObject*
  990. cm_repr(classmethod *cm)
  991. {
  992. return PyUnicode_FromFormat("<classmethod(%R)>", cm->cm_callable);
  993. }
  994. PyDoc_STRVAR(classmethod_doc,
  995. "classmethod(function) -> method\n\
  996. \n\
  997. Convert a function to be a class method.\n\
  998. \n\
  999. A class method receives the class as implicit first argument,\n\
  1000. just like an instance method receives the instance.\n\
  1001. To declare a class method, use this idiom:\n\
  1002. \n\
  1003. class C:\n\
  1004. @classmethod\n\
  1005. def f(cls, arg1, arg2, argN):\n\
  1006. ...\n\
  1007. \n\
  1008. It can be called either on the class (e.g. C.f()) or on an instance\n\
  1009. (e.g. C().f()). The instance is ignored except for its class.\n\
  1010. If a class method is called for a derived class, the derived class\n\
  1011. object is passed as the implied first argument.\n\
  1012. \n\
  1013. Class methods are different than C++ or Java static methods.\n\
  1014. If you want those, see the staticmethod builtin.");
  1015. PyTypeObject PyClassMethod_Type = {
  1016. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1017. "classmethod",
  1018. sizeof(classmethod),
  1019. 0,
  1020. (destructor)cm_dealloc, /* tp_dealloc */
  1021. 0, /* tp_vectorcall_offset */
  1022. 0, /* tp_getattr */
  1023. 0, /* tp_setattr */
  1024. 0, /* tp_as_async */
  1025. (reprfunc)cm_repr, /* tp_repr */
  1026. 0, /* tp_as_number */
  1027. 0, /* tp_as_sequence */
  1028. 0, /* tp_as_mapping */
  1029. 0, /* tp_hash */
  1030. 0, /* tp_call */
  1031. 0, /* tp_str */
  1032. 0, /* tp_getattro */
  1033. 0, /* tp_setattro */
  1034. 0, /* tp_as_buffer */
  1035. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
  1036. classmethod_doc, /* tp_doc */
  1037. (traverseproc)cm_traverse, /* tp_traverse */
  1038. (inquiry)cm_clear, /* tp_clear */
  1039. 0, /* tp_richcompare */
  1040. 0, /* tp_weaklistoffset */
  1041. 0, /* tp_iter */
  1042. 0, /* tp_iternext */
  1043. 0, /* tp_methods */
  1044. cm_memberlist, /* tp_members */
  1045. cm_getsetlist, /* tp_getset */
  1046. 0, /* tp_base */
  1047. 0, /* tp_dict */
  1048. cm_descr_get, /* tp_descr_get */
  1049. 0, /* tp_descr_set */
  1050. offsetof(classmethod, cm_dict), /* tp_dictoffset */
  1051. cm_init, /* tp_init */
  1052. PyType_GenericAlloc, /* tp_alloc */
  1053. PyType_GenericNew, /* tp_new */
  1054. PyObject_GC_Del, /* tp_free */
  1055. };
  1056. PyObject *
  1057. PyClassMethod_New(PyObject *callable)
  1058. {
  1059. classmethod *cm = (classmethod *)
  1060. PyType_GenericAlloc(&PyClassMethod_Type, 0);
  1061. if (cm != NULL) {
  1062. cm->cm_callable = Py_NewRef(callable);
  1063. }
  1064. return (PyObject *)cm;
  1065. }
  1066. /* Static method object */
  1067. /* A static method does not receive an implicit first argument.
  1068. To declare a static method, use this idiom:
  1069. class C:
  1070. @staticmethod
  1071. def f(arg1, arg2, argN):
  1072. ...
  1073. It can be called either on the class (e.g. C.f()) or on an instance
  1074. (e.g. C().f()). Both the class and the instance are ignored, and
  1075. neither is passed implicitly as the first argument to the method.
  1076. Static methods in Python are similar to those found in Java or C++.
  1077. For a more advanced concept, see class methods above.
  1078. */
  1079. typedef struct {
  1080. PyObject_HEAD
  1081. PyObject *sm_callable;
  1082. PyObject *sm_dict;
  1083. } staticmethod;
  1084. static void
  1085. sm_dealloc(staticmethod *sm)
  1086. {
  1087. _PyObject_GC_UNTRACK((PyObject *)sm);
  1088. Py_XDECREF(sm->sm_callable);
  1089. Py_XDECREF(sm->sm_dict);
  1090. Py_TYPE(sm)->tp_free((PyObject *)sm);
  1091. }
  1092. static int
  1093. sm_traverse(staticmethod *sm, visitproc visit, void *arg)
  1094. {
  1095. Py_VISIT(sm->sm_callable);
  1096. Py_VISIT(sm->sm_dict);
  1097. return 0;
  1098. }
  1099. static int
  1100. sm_clear(staticmethod *sm)
  1101. {
  1102. Py_CLEAR(sm->sm_callable);
  1103. Py_CLEAR(sm->sm_dict);
  1104. return 0;
  1105. }
  1106. static PyObject *
  1107. sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
  1108. {
  1109. staticmethod *sm = (staticmethod *)self;
  1110. if (sm->sm_callable == NULL) {
  1111. PyErr_SetString(PyExc_RuntimeError,
  1112. "uninitialized staticmethod object");
  1113. return NULL;
  1114. }
  1115. return Py_NewRef(sm->sm_callable);
  1116. }
  1117. static int
  1118. sm_init(PyObject *self, PyObject *args, PyObject *kwds)
  1119. {
  1120. staticmethod *sm = (staticmethod *)self;
  1121. PyObject *callable;
  1122. if (!_PyArg_NoKeywords("staticmethod", kwds))
  1123. return -1;
  1124. if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable))
  1125. return -1;
  1126. Py_XSETREF(sm->sm_callable, Py_NewRef(callable));
  1127. if (functools_wraps((PyObject *)sm, sm->sm_callable) < 0) {
  1128. return -1;
  1129. }
  1130. return 0;
  1131. }
  1132. static PyObject*
  1133. sm_call(PyObject *callable, PyObject *args, PyObject *kwargs)
  1134. {
  1135. staticmethod *sm = (staticmethod *)callable;
  1136. return PyObject_Call(sm->sm_callable, args, kwargs);
  1137. }
  1138. static PyMemberDef sm_memberlist[] = {
  1139. {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY},
  1140. {"__wrapped__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY},
  1141. {NULL} /* Sentinel */
  1142. };
  1143. static PyObject *
  1144. sm_get___isabstractmethod__(staticmethod *sm, void *closure)
  1145. {
  1146. int res = _PyObject_IsAbstract(sm->sm_callable);
  1147. if (res == -1) {
  1148. return NULL;
  1149. }
  1150. else if (res) {
  1151. Py_RETURN_TRUE;
  1152. }
  1153. Py_RETURN_FALSE;
  1154. }
  1155. static PyGetSetDef sm_getsetlist[] = {
  1156. {"__isabstractmethod__",
  1157. (getter)sm_get___isabstractmethod__, NULL, NULL, NULL},
  1158. {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
  1159. {NULL} /* Sentinel */
  1160. };
  1161. static PyObject*
  1162. sm_repr(staticmethod *sm)
  1163. {
  1164. return PyUnicode_FromFormat("<staticmethod(%R)>", sm->sm_callable);
  1165. }
  1166. PyDoc_STRVAR(staticmethod_doc,
  1167. "staticmethod(function) -> method\n\
  1168. \n\
  1169. Convert a function to be a static method.\n\
  1170. \n\
  1171. A static method does not receive an implicit first argument.\n\
  1172. To declare a static method, use this idiom:\n\
  1173. \n\
  1174. class C:\n\
  1175. @staticmethod\n\
  1176. def f(arg1, arg2, argN):\n\
  1177. ...\n\
  1178. \n\
  1179. It can be called either on the class (e.g. C.f()) or on an instance\n\
  1180. (e.g. C().f()). Both the class and the instance are ignored, and\n\
  1181. neither is passed implicitly as the first argument to the method.\n\
  1182. \n\
  1183. Static methods in Python are similar to those found in Java or C++.\n\
  1184. For a more advanced concept, see the classmethod builtin.");
  1185. PyTypeObject PyStaticMethod_Type = {
  1186. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1187. "staticmethod",
  1188. sizeof(staticmethod),
  1189. 0,
  1190. (destructor)sm_dealloc, /* tp_dealloc */
  1191. 0, /* tp_vectorcall_offset */
  1192. 0, /* tp_getattr */
  1193. 0, /* tp_setattr */
  1194. 0, /* tp_as_async */
  1195. (reprfunc)sm_repr, /* tp_repr */
  1196. 0, /* tp_as_number */
  1197. 0, /* tp_as_sequence */
  1198. 0, /* tp_as_mapping */
  1199. 0, /* tp_hash */
  1200. sm_call, /* tp_call */
  1201. 0, /* tp_str */
  1202. 0, /* tp_getattro */
  1203. 0, /* tp_setattro */
  1204. 0, /* tp_as_buffer */
  1205. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
  1206. staticmethod_doc, /* tp_doc */
  1207. (traverseproc)sm_traverse, /* tp_traverse */
  1208. (inquiry)sm_clear, /* tp_clear */
  1209. 0, /* tp_richcompare */
  1210. 0, /* tp_weaklistoffset */
  1211. 0, /* tp_iter */
  1212. 0, /* tp_iternext */
  1213. 0, /* tp_methods */
  1214. sm_memberlist, /* tp_members */
  1215. sm_getsetlist, /* tp_getset */
  1216. 0, /* tp_base */
  1217. 0, /* tp_dict */
  1218. sm_descr_get, /* tp_descr_get */
  1219. 0, /* tp_descr_set */
  1220. offsetof(staticmethod, sm_dict), /* tp_dictoffset */
  1221. sm_init, /* tp_init */
  1222. PyType_GenericAlloc, /* tp_alloc */
  1223. PyType_GenericNew, /* tp_new */
  1224. PyObject_GC_Del, /* tp_free */
  1225. };
  1226. PyObject *
  1227. PyStaticMethod_New(PyObject *callable)
  1228. {
  1229. staticmethod *sm = (staticmethod *)
  1230. PyType_GenericAlloc(&PyStaticMethod_Type, 0);
  1231. if (sm != NULL) {
  1232. sm->sm_callable = Py_NewRef(callable);
  1233. }
  1234. return (PyObject *)sm;
  1235. }