You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1047 lines
31 KiB

36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
PEP 227 implementation The majority of the changes are in the compiler. The mainloop changes primarily to implement the new opcodes and to pass a function's closure to eval_code2(). Frames and functions got new slots to hold the closure. Include/compile.h Add co_freevars and co_cellvars slots to code objects. Update PyCode_New() to take freevars and cellvars as arguments Include/funcobject.h Add func_closure slot to function objects. Add GetClosure()/SetClosure() functions (and corresponding macros) for getting at the closure. Include/frameobject.h PyFrame_New() now takes a closure. Include/opcode.h Add four new opcodes: MAKE_CLOSURE, LOAD_CLOSURE, LOAD_DEREF, STORE_DEREF. Remove comment about old requirement for opcodes to fit in 7 bits. compile.c Implement changes to code objects for co_freevars and co_cellvars. Modify symbol table to use st_cur_name (string object for the name of the current scope) and st_cur_children (list of nested blocks). Also define st_nested, which might more properly be called st_cur_nested. Add several DEF_XXX flags to track def-use information for free variables. New or modified functions of note: com_make_closure(struct compiling *, PyCodeObject *) Emit LOAD_CLOSURE opcodes as needed to pass cells for free variables into nested scope. com_addop_varname(struct compiling *, int, char *) Emits opcodes for LOAD_DEREF and STORE_DEREF. get_ref_type(struct compiling *, char *name) Return NAME_CLOSURE if ref type is FREE or CELL symtable_load_symbols(struct compiling *) Decides what variables are cell or free based on def-use info. Can now raise SyntaxError if nested scopes are mixed with exec or from blah import *. make_scope_info(PyObject *, PyObject *, int, int) Helper functions for symtable scope stack. symtable_update_free_vars(struct symtable *) After a code block has been analyzed, it must check each of its children for free variables that are not defined in the block. If a variable is free in a child and not defined in the parent, then it is defined by block the enclosing the current one or it is a global. This does the right logic. symtable_add_use() is now a macro for symtable_add_def() symtable_assign(struct symtable *, node *) Use goto instead of for (;;) Fixed bug in symtable where name of keyword argument in function call was treated as assignment in the scope of the call site. Ex: def f(): g(a=2) # a was considered a local of f ceval.c eval_code2() now take one more argument, a closure. Implement LOAD_CLOSURE, LOAD_DEREF, STORE_DEREF, MAKE_CLOSURE> Also: When name error occurs for global variable, report that the name was global in the error mesage. Objects/frameobject.c Initialize f_closure to be a tuple containing space for cellvars and freevars. f_closure is NULL if neither are present. Objects/funcobject.c Add support for func_closure. Python/import.c Change the magic number. Python/marshal.c Track changes to code objects.
25 years ago
PEP 227 implementation The majority of the changes are in the compiler. The mainloop changes primarily to implement the new opcodes and to pass a function's closure to eval_code2(). Frames and functions got new slots to hold the closure. Include/compile.h Add co_freevars and co_cellvars slots to code objects. Update PyCode_New() to take freevars and cellvars as arguments Include/funcobject.h Add func_closure slot to function objects. Add GetClosure()/SetClosure() functions (and corresponding macros) for getting at the closure. Include/frameobject.h PyFrame_New() now takes a closure. Include/opcode.h Add four new opcodes: MAKE_CLOSURE, LOAD_CLOSURE, LOAD_DEREF, STORE_DEREF. Remove comment about old requirement for opcodes to fit in 7 bits. compile.c Implement changes to code objects for co_freevars and co_cellvars. Modify symbol table to use st_cur_name (string object for the name of the current scope) and st_cur_children (list of nested blocks). Also define st_nested, which might more properly be called st_cur_nested. Add several DEF_XXX flags to track def-use information for free variables. New or modified functions of note: com_make_closure(struct compiling *, PyCodeObject *) Emit LOAD_CLOSURE opcodes as needed to pass cells for free variables into nested scope. com_addop_varname(struct compiling *, int, char *) Emits opcodes for LOAD_DEREF and STORE_DEREF. get_ref_type(struct compiling *, char *name) Return NAME_CLOSURE if ref type is FREE or CELL symtable_load_symbols(struct compiling *) Decides what variables are cell or free based on def-use info. Can now raise SyntaxError if nested scopes are mixed with exec or from blah import *. make_scope_info(PyObject *, PyObject *, int, int) Helper functions for symtable scope stack. symtable_update_free_vars(struct symtable *) After a code block has been analyzed, it must check each of its children for free variables that are not defined in the block. If a variable is free in a child and not defined in the parent, then it is defined by block the enclosing the current one or it is a global. This does the right logic. symtable_add_use() is now a macro for symtable_add_def() symtable_assign(struct symtable *, node *) Use goto instead of for (;;) Fixed bug in symtable where name of keyword argument in function call was treated as assignment in the scope of the call site. Ex: def f(): g(a=2) # a was considered a local of f ceval.c eval_code2() now take one more argument, a closure. Implement LOAD_CLOSURE, LOAD_DEREF, STORE_DEREF, MAKE_CLOSURE> Also: When name error occurs for global variable, report that the name was global in the error mesage. Objects/frameobject.c Initialize f_closure to be a tuple containing space for cellvars and freevars. f_closure is NULL if neither are present. Objects/funcobject.c Add support for func_closure. Python/import.c Change the magic number. Python/marshal.c Track changes to code objects.
25 years ago
PEP 227 implementation The majority of the changes are in the compiler. The mainloop changes primarily to implement the new opcodes and to pass a function's closure to eval_code2(). Frames and functions got new slots to hold the closure. Include/compile.h Add co_freevars and co_cellvars slots to code objects. Update PyCode_New() to take freevars and cellvars as arguments Include/funcobject.h Add func_closure slot to function objects. Add GetClosure()/SetClosure() functions (and corresponding macros) for getting at the closure. Include/frameobject.h PyFrame_New() now takes a closure. Include/opcode.h Add four new opcodes: MAKE_CLOSURE, LOAD_CLOSURE, LOAD_DEREF, STORE_DEREF. Remove comment about old requirement for opcodes to fit in 7 bits. compile.c Implement changes to code objects for co_freevars and co_cellvars. Modify symbol table to use st_cur_name (string object for the name of the current scope) and st_cur_children (list of nested blocks). Also define st_nested, which might more properly be called st_cur_nested. Add several DEF_XXX flags to track def-use information for free variables. New or modified functions of note: com_make_closure(struct compiling *, PyCodeObject *) Emit LOAD_CLOSURE opcodes as needed to pass cells for free variables into nested scope. com_addop_varname(struct compiling *, int, char *) Emits opcodes for LOAD_DEREF and STORE_DEREF. get_ref_type(struct compiling *, char *name) Return NAME_CLOSURE if ref type is FREE or CELL symtable_load_symbols(struct compiling *) Decides what variables are cell or free based on def-use info. Can now raise SyntaxError if nested scopes are mixed with exec or from blah import *. make_scope_info(PyObject *, PyObject *, int, int) Helper functions for symtable scope stack. symtable_update_free_vars(struct symtable *) After a code block has been analyzed, it must check each of its children for free variables that are not defined in the block. If a variable is free in a child and not defined in the parent, then it is defined by block the enclosing the current one or it is a global. This does the right logic. symtable_add_use() is now a macro for symtable_add_def() symtable_assign(struct symtable *, node *) Use goto instead of for (;;) Fixed bug in symtable where name of keyword argument in function call was treated as assignment in the scope of the call site. Ex: def f(): g(a=2) # a was considered a local of f ceval.c eval_code2() now take one more argument, a closure. Implement LOAD_CLOSURE, LOAD_DEREF, STORE_DEREF, MAKE_CLOSURE> Also: When name error occurs for global variable, report that the name was global in the error mesage. Objects/frameobject.c Initialize f_closure to be a tuple containing space for cellvars and freevars. f_closure is NULL if neither are present. Objects/funcobject.c Add support for func_closure. Python/import.c Change the magic number. Python/marshal.c Track changes to code objects.
25 years ago
36 years ago
36 years ago
36 years ago
36 years ago
14 years ago
14 years ago
14 years ago
36 years ago
  1. /* Function object implementation */
  2. #include "Python.h"
  3. #include "pycore_object.h"
  4. #include "pycore_pymem.h"
  5. #include "pycore_pystate.h"
  6. #include "pycore_tupleobject.h"
  7. #include "code.h"
  8. #include "structmember.h"
  9. PyObject *
  10. PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
  11. {
  12. PyFunctionObject *op;
  13. PyObject *doc, *consts, *module;
  14. static PyObject *__name__ = NULL;
  15. if (__name__ == NULL) {
  16. __name__ = PyUnicode_InternFromString("__name__");
  17. if (__name__ == NULL)
  18. return NULL;
  19. }
  20. op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
  21. if (op == NULL)
  22. return NULL;
  23. op->func_weakreflist = NULL;
  24. Py_INCREF(code);
  25. op->func_code = code;
  26. Py_INCREF(globals);
  27. op->func_globals = globals;
  28. op->func_name = ((PyCodeObject *)code)->co_name;
  29. Py_INCREF(op->func_name);
  30. op->func_defaults = NULL; /* No default arguments */
  31. op->func_kwdefaults = NULL; /* No keyword only defaults */
  32. op->func_closure = NULL;
  33. op->vectorcall = _PyFunction_Vectorcall;
  34. consts = ((PyCodeObject *)code)->co_consts;
  35. if (PyTuple_Size(consts) >= 1) {
  36. doc = PyTuple_GetItem(consts, 0);
  37. if (!PyUnicode_Check(doc))
  38. doc = Py_None;
  39. }
  40. else
  41. doc = Py_None;
  42. Py_INCREF(doc);
  43. op->func_doc = doc;
  44. op->func_dict = NULL;
  45. op->func_module = NULL;
  46. op->func_annotations = NULL;
  47. /* __module__: If module name is in globals, use it.
  48. Otherwise, use None. */
  49. module = PyDict_GetItemWithError(globals, __name__);
  50. if (module) {
  51. Py_INCREF(module);
  52. op->func_module = module;
  53. }
  54. else if (PyErr_Occurred()) {
  55. Py_DECREF(op);
  56. return NULL;
  57. }
  58. if (qualname)
  59. op->func_qualname = qualname;
  60. else
  61. op->func_qualname = op->func_name;
  62. Py_INCREF(op->func_qualname);
  63. _PyObject_GC_TRACK(op);
  64. return (PyObject *)op;
  65. }
  66. PyObject *
  67. PyFunction_New(PyObject *code, PyObject *globals)
  68. {
  69. return PyFunction_NewWithQualName(code, globals, NULL);
  70. }
  71. PyObject *
  72. PyFunction_GetCode(PyObject *op)
  73. {
  74. if (!PyFunction_Check(op)) {
  75. PyErr_BadInternalCall();
  76. return NULL;
  77. }
  78. return ((PyFunctionObject *) op) -> func_code;
  79. }
  80. PyObject *
  81. PyFunction_GetGlobals(PyObject *op)
  82. {
  83. if (!PyFunction_Check(op)) {
  84. PyErr_BadInternalCall();
  85. return NULL;
  86. }
  87. return ((PyFunctionObject *) op) -> func_globals;
  88. }
  89. PyObject *
  90. PyFunction_GetModule(PyObject *op)
  91. {
  92. if (!PyFunction_Check(op)) {
  93. PyErr_BadInternalCall();
  94. return NULL;
  95. }
  96. return ((PyFunctionObject *) op) -> func_module;
  97. }
  98. PyObject *
  99. PyFunction_GetDefaults(PyObject *op)
  100. {
  101. if (!PyFunction_Check(op)) {
  102. PyErr_BadInternalCall();
  103. return NULL;
  104. }
  105. return ((PyFunctionObject *) op) -> func_defaults;
  106. }
  107. int
  108. PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
  109. {
  110. if (!PyFunction_Check(op)) {
  111. PyErr_BadInternalCall();
  112. return -1;
  113. }
  114. if (defaults == Py_None)
  115. defaults = NULL;
  116. else if (defaults && PyTuple_Check(defaults)) {
  117. Py_INCREF(defaults);
  118. }
  119. else {
  120. PyErr_SetString(PyExc_SystemError, "non-tuple default args");
  121. return -1;
  122. }
  123. Py_XSETREF(((PyFunctionObject *)op)->func_defaults, defaults);
  124. return 0;
  125. }
  126. PyObject *
  127. PyFunction_GetKwDefaults(PyObject *op)
  128. {
  129. if (!PyFunction_Check(op)) {
  130. PyErr_BadInternalCall();
  131. return NULL;
  132. }
  133. return ((PyFunctionObject *) op) -> func_kwdefaults;
  134. }
  135. int
  136. PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults)
  137. {
  138. if (!PyFunction_Check(op)) {
  139. PyErr_BadInternalCall();
  140. return -1;
  141. }
  142. if (defaults == Py_None)
  143. defaults = NULL;
  144. else if (defaults && PyDict_Check(defaults)) {
  145. Py_INCREF(defaults);
  146. }
  147. else {
  148. PyErr_SetString(PyExc_SystemError,
  149. "non-dict keyword only default args");
  150. return -1;
  151. }
  152. Py_XSETREF(((PyFunctionObject *)op)->func_kwdefaults, defaults);
  153. return 0;
  154. }
  155. PyObject *
  156. PyFunction_GetClosure(PyObject *op)
  157. {
  158. if (!PyFunction_Check(op)) {
  159. PyErr_BadInternalCall();
  160. return NULL;
  161. }
  162. return ((PyFunctionObject *) op) -> func_closure;
  163. }
  164. int
  165. PyFunction_SetClosure(PyObject *op, PyObject *closure)
  166. {
  167. if (!PyFunction_Check(op)) {
  168. PyErr_BadInternalCall();
  169. return -1;
  170. }
  171. if (closure == Py_None)
  172. closure = NULL;
  173. else if (PyTuple_Check(closure)) {
  174. Py_INCREF(closure);
  175. }
  176. else {
  177. PyErr_Format(PyExc_SystemError,
  178. "expected tuple for closure, got '%.100s'",
  179. closure->ob_type->tp_name);
  180. return -1;
  181. }
  182. Py_XSETREF(((PyFunctionObject *)op)->func_closure, closure);
  183. return 0;
  184. }
  185. PyObject *
  186. PyFunction_GetAnnotations(PyObject *op)
  187. {
  188. if (!PyFunction_Check(op)) {
  189. PyErr_BadInternalCall();
  190. return NULL;
  191. }
  192. return ((PyFunctionObject *) op) -> func_annotations;
  193. }
  194. int
  195. PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)
  196. {
  197. if (!PyFunction_Check(op)) {
  198. PyErr_BadInternalCall();
  199. return -1;
  200. }
  201. if (annotations == Py_None)
  202. annotations = NULL;
  203. else if (annotations && PyDict_Check(annotations)) {
  204. Py_INCREF(annotations);
  205. }
  206. else {
  207. PyErr_SetString(PyExc_SystemError,
  208. "non-dict annotations");
  209. return -1;
  210. }
  211. Py_XSETREF(((PyFunctionObject *)op)->func_annotations, annotations);
  212. return 0;
  213. }
  214. /* Methods */
  215. #define OFF(x) offsetof(PyFunctionObject, x)
  216. static PyMemberDef func_memberlist[] = {
  217. {"__closure__", T_OBJECT, OFF(func_closure),
  218. RESTRICTED|READONLY},
  219. {"__doc__", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED},
  220. {"__globals__", T_OBJECT, OFF(func_globals),
  221. RESTRICTED|READONLY},
  222. {"__module__", T_OBJECT, OFF(func_module), PY_WRITE_RESTRICTED},
  223. {NULL} /* Sentinel */
  224. };
  225. static PyObject *
  226. func_get_code(PyFunctionObject *op, void *Py_UNUSED(ignored))
  227. {
  228. if (PySys_Audit("object.__getattr__", "Os", op, "__code__") < 0) {
  229. return NULL;
  230. }
  231. Py_INCREF(op->func_code);
  232. return op->func_code;
  233. }
  234. static int
  235. func_set_code(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
  236. {
  237. Py_ssize_t nfree, nclosure;
  238. /* Not legal to del f.func_code or to set it to anything
  239. * other than a code object. */
  240. if (value == NULL || !PyCode_Check(value)) {
  241. PyErr_SetString(PyExc_TypeError,
  242. "__code__ must be set to a code object");
  243. return -1;
  244. }
  245. if (PySys_Audit("object.__setattr__", "OsO",
  246. op, "__code__", value) < 0) {
  247. return -1;
  248. }
  249. nfree = PyCode_GetNumFree((PyCodeObject *)value);
  250. nclosure = (op->func_closure == NULL ? 0 :
  251. PyTuple_GET_SIZE(op->func_closure));
  252. if (nclosure != nfree) {
  253. PyErr_Format(PyExc_ValueError,
  254. "%U() requires a code object with %zd free vars,"
  255. " not %zd",
  256. op->func_name,
  257. nclosure, nfree);
  258. return -1;
  259. }
  260. Py_INCREF(value);
  261. Py_XSETREF(op->func_code, value);
  262. return 0;
  263. }
  264. static PyObject *
  265. func_get_name(PyFunctionObject *op, void *Py_UNUSED(ignored))
  266. {
  267. Py_INCREF(op->func_name);
  268. return op->func_name;
  269. }
  270. static int
  271. func_set_name(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
  272. {
  273. /* Not legal to del f.func_name or to set it to anything
  274. * other than a string object. */
  275. if (value == NULL || !PyUnicode_Check(value)) {
  276. PyErr_SetString(PyExc_TypeError,
  277. "__name__ must be set to a string object");
  278. return -1;
  279. }
  280. Py_INCREF(value);
  281. Py_XSETREF(op->func_name, value);
  282. return 0;
  283. }
  284. static PyObject *
  285. func_get_qualname(PyFunctionObject *op, void *Py_UNUSED(ignored))
  286. {
  287. Py_INCREF(op->func_qualname);
  288. return op->func_qualname;
  289. }
  290. static int
  291. func_set_qualname(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
  292. {
  293. /* Not legal to del f.__qualname__ or to set it to anything
  294. * other than a string object. */
  295. if (value == NULL || !PyUnicode_Check(value)) {
  296. PyErr_SetString(PyExc_TypeError,
  297. "__qualname__ must be set to a string object");
  298. return -1;
  299. }
  300. Py_INCREF(value);
  301. Py_XSETREF(op->func_qualname, value);
  302. return 0;
  303. }
  304. static PyObject *
  305. func_get_defaults(PyFunctionObject *op, void *Py_UNUSED(ignored))
  306. {
  307. if (PySys_Audit("object.__getattr__", "Os", op, "__defaults__") < 0) {
  308. return NULL;
  309. }
  310. if (op->func_defaults == NULL) {
  311. Py_RETURN_NONE;
  312. }
  313. Py_INCREF(op->func_defaults);
  314. return op->func_defaults;
  315. }
  316. static int
  317. func_set_defaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
  318. {
  319. /* Legal to del f.func_defaults.
  320. * Can only set func_defaults to NULL or a tuple. */
  321. if (value == Py_None)
  322. value = NULL;
  323. if (value != NULL && !PyTuple_Check(value)) {
  324. PyErr_SetString(PyExc_TypeError,
  325. "__defaults__ must be set to a tuple object");
  326. return -1;
  327. }
  328. if (value) {
  329. if (PySys_Audit("object.__setattr__", "OsO",
  330. op, "__defaults__", value) < 0) {
  331. return -1;
  332. }
  333. } else if (PySys_Audit("object.__delattr__", "Os",
  334. op, "__defaults__") < 0) {
  335. return -1;
  336. }
  337. Py_XINCREF(value);
  338. Py_XSETREF(op->func_defaults, value);
  339. return 0;
  340. }
  341. static PyObject *
  342. func_get_kwdefaults(PyFunctionObject *op, void *Py_UNUSED(ignored))
  343. {
  344. if (PySys_Audit("object.__getattr__", "Os",
  345. op, "__kwdefaults__") < 0) {
  346. return NULL;
  347. }
  348. if (op->func_kwdefaults == NULL) {
  349. Py_RETURN_NONE;
  350. }
  351. Py_INCREF(op->func_kwdefaults);
  352. return op->func_kwdefaults;
  353. }
  354. static int
  355. func_set_kwdefaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
  356. {
  357. if (value == Py_None)
  358. value = NULL;
  359. /* Legal to del f.func_kwdefaults.
  360. * Can only set func_kwdefaults to NULL or a dict. */
  361. if (value != NULL && !PyDict_Check(value)) {
  362. PyErr_SetString(PyExc_TypeError,
  363. "__kwdefaults__ must be set to a dict object");
  364. return -1;
  365. }
  366. if (value) {
  367. if (PySys_Audit("object.__setattr__", "OsO",
  368. op, "__kwdefaults__", value) < 0) {
  369. return -1;
  370. }
  371. } else if (PySys_Audit("object.__delattr__", "Os",
  372. op, "__kwdefaults__") < 0) {
  373. return -1;
  374. }
  375. Py_XINCREF(value);
  376. Py_XSETREF(op->func_kwdefaults, value);
  377. return 0;
  378. }
  379. static PyObject *
  380. func_get_annotations(PyFunctionObject *op, void *Py_UNUSED(ignored))
  381. {
  382. if (op->func_annotations == NULL) {
  383. op->func_annotations = PyDict_New();
  384. if (op->func_annotations == NULL)
  385. return NULL;
  386. }
  387. Py_INCREF(op->func_annotations);
  388. return op->func_annotations;
  389. }
  390. static int
  391. func_set_annotations(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
  392. {
  393. if (value == Py_None)
  394. value = NULL;
  395. /* Legal to del f.func_annotations.
  396. * Can only set func_annotations to NULL (through C api)
  397. * or a dict. */
  398. if (value != NULL && !PyDict_Check(value)) {
  399. PyErr_SetString(PyExc_TypeError,
  400. "__annotations__ must be set to a dict object");
  401. return -1;
  402. }
  403. Py_XINCREF(value);
  404. Py_XSETREF(op->func_annotations, value);
  405. return 0;
  406. }
  407. static PyGetSetDef func_getsetlist[] = {
  408. {"__code__", (getter)func_get_code, (setter)func_set_code},
  409. {"__defaults__", (getter)func_get_defaults,
  410. (setter)func_set_defaults},
  411. {"__kwdefaults__", (getter)func_get_kwdefaults,
  412. (setter)func_set_kwdefaults},
  413. {"__annotations__", (getter)func_get_annotations,
  414. (setter)func_set_annotations},
  415. {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
  416. {"__name__", (getter)func_get_name, (setter)func_set_name},
  417. {"__qualname__", (getter)func_get_qualname, (setter)func_set_qualname},
  418. {NULL} /* Sentinel */
  419. };
  420. /*[clinic input]
  421. class function "PyFunctionObject *" "&PyFunction_Type"
  422. [clinic start generated code]*/
  423. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=70af9c90aa2e71b0]*/
  424. #include "clinic/funcobject.c.h"
  425. /* function.__new__() maintains the following invariants for closures.
  426. The closure must correspond to the free variables of the code object.
  427. if len(code.co_freevars) == 0:
  428. closure = NULL
  429. else:
  430. len(closure) == len(code.co_freevars)
  431. for every elt in closure, type(elt) == cell
  432. */
  433. /*[clinic input]
  434. @classmethod
  435. function.__new__ as func_new
  436. code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
  437. a code object
  438. globals: object(subclass_of="&PyDict_Type")
  439. the globals dictionary
  440. name: object = None
  441. a string that overrides the name from the code object
  442. argdefs as defaults: object = None
  443. a tuple that specifies the default argument values
  444. closure: object = None
  445. a tuple that supplies the bindings for free variables
  446. Create a function object.
  447. [clinic start generated code]*/
  448. static PyObject *
  449. func_new_impl(PyTypeObject *type, PyCodeObject *code, PyObject *globals,
  450. PyObject *name, PyObject *defaults, PyObject *closure)
  451. /*[clinic end generated code: output=99c6d9da3a24e3be input=93611752fc2daf11]*/
  452. {
  453. PyFunctionObject *newfunc;
  454. Py_ssize_t nfree, nclosure;
  455. if (name != Py_None && !PyUnicode_Check(name)) {
  456. PyErr_SetString(PyExc_TypeError,
  457. "arg 3 (name) must be None or string");
  458. return NULL;
  459. }
  460. if (defaults != Py_None && !PyTuple_Check(defaults)) {
  461. PyErr_SetString(PyExc_TypeError,
  462. "arg 4 (defaults) must be None or tuple");
  463. return NULL;
  464. }
  465. nfree = PyTuple_GET_SIZE(code->co_freevars);
  466. if (!PyTuple_Check(closure)) {
  467. if (nfree && closure == Py_None) {
  468. PyErr_SetString(PyExc_TypeError,
  469. "arg 5 (closure) must be tuple");
  470. return NULL;
  471. }
  472. else if (closure != Py_None) {
  473. PyErr_SetString(PyExc_TypeError,
  474. "arg 5 (closure) must be None or tuple");
  475. return NULL;
  476. }
  477. }
  478. /* check that the closure is well-formed */
  479. nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
  480. if (nfree != nclosure)
  481. return PyErr_Format(PyExc_ValueError,
  482. "%U requires closure of length %zd, not %zd",
  483. code->co_name, nfree, nclosure);
  484. if (nclosure) {
  485. Py_ssize_t i;
  486. for (i = 0; i < nclosure; i++) {
  487. PyObject *o = PyTuple_GET_ITEM(closure, i);
  488. if (!PyCell_Check(o)) {
  489. return PyErr_Format(PyExc_TypeError,
  490. "arg 5 (closure) expected cell, found %s",
  491. o->ob_type->tp_name);
  492. }
  493. }
  494. }
  495. if (PySys_Audit("function.__new__", "O", code) < 0) {
  496. return NULL;
  497. }
  498. newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
  499. globals);
  500. if (newfunc == NULL)
  501. return NULL;
  502. if (name != Py_None) {
  503. Py_INCREF(name);
  504. Py_SETREF(newfunc->func_name, name);
  505. }
  506. if (defaults != Py_None) {
  507. Py_INCREF(defaults);
  508. newfunc->func_defaults = defaults;
  509. }
  510. if (closure != Py_None) {
  511. Py_INCREF(closure);
  512. newfunc->func_closure = closure;
  513. }
  514. return (PyObject *)newfunc;
  515. }
  516. static int
  517. func_clear(PyFunctionObject *op)
  518. {
  519. Py_CLEAR(op->func_code);
  520. Py_CLEAR(op->func_globals);
  521. Py_CLEAR(op->func_module);
  522. Py_CLEAR(op->func_name);
  523. Py_CLEAR(op->func_defaults);
  524. Py_CLEAR(op->func_kwdefaults);
  525. Py_CLEAR(op->func_doc);
  526. Py_CLEAR(op->func_dict);
  527. Py_CLEAR(op->func_closure);
  528. Py_CLEAR(op->func_annotations);
  529. Py_CLEAR(op->func_qualname);
  530. return 0;
  531. }
  532. static void
  533. func_dealloc(PyFunctionObject *op)
  534. {
  535. _PyObject_GC_UNTRACK(op);
  536. if (op->func_weakreflist != NULL) {
  537. PyObject_ClearWeakRefs((PyObject *) op);
  538. }
  539. (void)func_clear(op);
  540. PyObject_GC_Del(op);
  541. }
  542. static PyObject*
  543. func_repr(PyFunctionObject *op)
  544. {
  545. return PyUnicode_FromFormat("<function %U at %p>",
  546. op->func_qualname, op);
  547. }
  548. static int
  549. func_traverse(PyFunctionObject *f, visitproc visit, void *arg)
  550. {
  551. Py_VISIT(f->func_code);
  552. Py_VISIT(f->func_globals);
  553. Py_VISIT(f->func_module);
  554. Py_VISIT(f->func_defaults);
  555. Py_VISIT(f->func_kwdefaults);
  556. Py_VISIT(f->func_doc);
  557. Py_VISIT(f->func_name);
  558. Py_VISIT(f->func_dict);
  559. Py_VISIT(f->func_closure);
  560. Py_VISIT(f->func_annotations);
  561. Py_VISIT(f->func_qualname);
  562. return 0;
  563. }
  564. /* Bind a function to an object */
  565. static PyObject *
  566. func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
  567. {
  568. if (obj == Py_None || obj == NULL) {
  569. Py_INCREF(func);
  570. return func;
  571. }
  572. return PyMethod_New(func, obj);
  573. }
  574. PyTypeObject PyFunction_Type = {
  575. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  576. "function",
  577. sizeof(PyFunctionObject),
  578. 0,
  579. (destructor)func_dealloc, /* tp_dealloc */
  580. offsetof(PyFunctionObject, vectorcall), /* tp_vectorcall_offset */
  581. 0, /* tp_getattr */
  582. 0, /* tp_setattr */
  583. 0, /* tp_as_async */
  584. (reprfunc)func_repr, /* tp_repr */
  585. 0, /* tp_as_number */
  586. 0, /* tp_as_sequence */
  587. 0, /* tp_as_mapping */
  588. 0, /* tp_hash */
  589. PyVectorcall_Call, /* tp_call */
  590. 0, /* tp_str */
  591. 0, /* tp_getattro */
  592. 0, /* tp_setattro */
  593. 0, /* tp_as_buffer */
  594. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  595. _Py_TPFLAGS_HAVE_VECTORCALL |
  596. Py_TPFLAGS_METHOD_DESCRIPTOR, /* tp_flags */
  597. func_new__doc__, /* tp_doc */
  598. (traverseproc)func_traverse, /* tp_traverse */
  599. (inquiry)func_clear, /* tp_clear */
  600. 0, /* tp_richcompare */
  601. offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
  602. 0, /* tp_iter */
  603. 0, /* tp_iternext */
  604. 0, /* tp_methods */
  605. func_memberlist, /* tp_members */
  606. func_getsetlist, /* tp_getset */
  607. 0, /* tp_base */
  608. 0, /* tp_dict */
  609. func_descr_get, /* tp_descr_get */
  610. 0, /* tp_descr_set */
  611. offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */
  612. 0, /* tp_init */
  613. 0, /* tp_alloc */
  614. func_new, /* tp_new */
  615. };
  616. /* Class method object */
  617. /* A class method receives the class as implicit first argument,
  618. just like an instance method receives the instance.
  619. To declare a class method, use this idiom:
  620. class C:
  621. @classmethod
  622. def f(cls, arg1, arg2, ...):
  623. ...
  624. It can be called either on the class (e.g. C.f()) or on an instance
  625. (e.g. C().f()); the instance is ignored except for its class.
  626. If a class method is called for a derived class, the derived class
  627. object is passed as the implied first argument.
  628. Class methods are different than C++ or Java static methods.
  629. If you want those, see static methods below.
  630. */
  631. typedef struct {
  632. PyObject_HEAD
  633. PyObject *cm_callable;
  634. PyObject *cm_dict;
  635. } classmethod;
  636. static void
  637. cm_dealloc(classmethod *cm)
  638. {
  639. _PyObject_GC_UNTRACK((PyObject *)cm);
  640. Py_XDECREF(cm->cm_callable);
  641. Py_XDECREF(cm->cm_dict);
  642. Py_TYPE(cm)->tp_free((PyObject *)cm);
  643. }
  644. static int
  645. cm_traverse(classmethod *cm, visitproc visit, void *arg)
  646. {
  647. Py_VISIT(cm->cm_callable);
  648. Py_VISIT(cm->cm_dict);
  649. return 0;
  650. }
  651. static int
  652. cm_clear(classmethod *cm)
  653. {
  654. Py_CLEAR(cm->cm_callable);
  655. Py_CLEAR(cm->cm_dict);
  656. return 0;
  657. }
  658. static PyObject *
  659. cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
  660. {
  661. classmethod *cm = (classmethod *)self;
  662. if (cm->cm_callable == NULL) {
  663. PyErr_SetString(PyExc_RuntimeError,
  664. "uninitialized classmethod object");
  665. return NULL;
  666. }
  667. if (type == NULL)
  668. type = (PyObject *)(Py_TYPE(obj));
  669. if (Py_TYPE(cm->cm_callable)->tp_descr_get != NULL) {
  670. return Py_TYPE(cm->cm_callable)->tp_descr_get(cm->cm_callable, type,
  671. NULL);
  672. }
  673. return PyMethod_New(cm->cm_callable, type);
  674. }
  675. static int
  676. cm_init(PyObject *self, PyObject *args, PyObject *kwds)
  677. {
  678. classmethod *cm = (classmethod *)self;
  679. PyObject *callable;
  680. if (!_PyArg_NoKeywords("classmethod", kwds))
  681. return -1;
  682. if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable))
  683. return -1;
  684. Py_INCREF(callable);
  685. Py_XSETREF(cm->cm_callable, callable);
  686. return 0;
  687. }
  688. static PyMemberDef cm_memberlist[] = {
  689. {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY},
  690. {NULL} /* Sentinel */
  691. };
  692. static PyObject *
  693. cm_get___isabstractmethod__(classmethod *cm, void *closure)
  694. {
  695. int res = _PyObject_IsAbstract(cm->cm_callable);
  696. if (res == -1) {
  697. return NULL;
  698. }
  699. else if (res) {
  700. Py_RETURN_TRUE;
  701. }
  702. Py_RETURN_FALSE;
  703. }
  704. static PyGetSetDef cm_getsetlist[] = {
  705. {"__isabstractmethod__",
  706. (getter)cm_get___isabstractmethod__, NULL,
  707. NULL,
  708. NULL},
  709. {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
  710. {NULL} /* Sentinel */
  711. };
  712. PyDoc_STRVAR(classmethod_doc,
  713. "classmethod(function) -> method\n\
  714. \n\
  715. Convert a function to be a class method.\n\
  716. \n\
  717. A class method receives the class as implicit first argument,\n\
  718. just like an instance method receives the instance.\n\
  719. To declare a class method, use this idiom:\n\
  720. \n\
  721. class C:\n\
  722. @classmethod\n\
  723. def f(cls, arg1, arg2, ...):\n\
  724. ...\n\
  725. \n\
  726. It can be called either on the class (e.g. C.f()) or on an instance\n\
  727. (e.g. C().f()). The instance is ignored except for its class.\n\
  728. If a class method is called for a derived class, the derived class\n\
  729. object is passed as the implied first argument.\n\
  730. \n\
  731. Class methods are different than C++ or Java static methods.\n\
  732. If you want those, see the staticmethod builtin.");
  733. PyTypeObject PyClassMethod_Type = {
  734. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  735. "classmethod",
  736. sizeof(classmethod),
  737. 0,
  738. (destructor)cm_dealloc, /* tp_dealloc */
  739. 0, /* tp_vectorcall_offset */
  740. 0, /* tp_getattr */
  741. 0, /* tp_setattr */
  742. 0, /* tp_as_async */
  743. 0, /* tp_repr */
  744. 0, /* tp_as_number */
  745. 0, /* tp_as_sequence */
  746. 0, /* tp_as_mapping */
  747. 0, /* tp_hash */
  748. 0, /* tp_call */
  749. 0, /* tp_str */
  750. 0, /* tp_getattro */
  751. 0, /* tp_setattro */
  752. 0, /* tp_as_buffer */
  753. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
  754. classmethod_doc, /* tp_doc */
  755. (traverseproc)cm_traverse, /* tp_traverse */
  756. (inquiry)cm_clear, /* tp_clear */
  757. 0, /* tp_richcompare */
  758. 0, /* tp_weaklistoffset */
  759. 0, /* tp_iter */
  760. 0, /* tp_iternext */
  761. 0, /* tp_methods */
  762. cm_memberlist, /* tp_members */
  763. cm_getsetlist, /* tp_getset */
  764. 0, /* tp_base */
  765. 0, /* tp_dict */
  766. cm_descr_get, /* tp_descr_get */
  767. 0, /* tp_descr_set */
  768. offsetof(classmethod, cm_dict), /* tp_dictoffset */
  769. cm_init, /* tp_init */
  770. PyType_GenericAlloc, /* tp_alloc */
  771. PyType_GenericNew, /* tp_new */
  772. PyObject_GC_Del, /* tp_free */
  773. };
  774. PyObject *
  775. PyClassMethod_New(PyObject *callable)
  776. {
  777. classmethod *cm = (classmethod *)
  778. PyType_GenericAlloc(&PyClassMethod_Type, 0);
  779. if (cm != NULL) {
  780. Py_INCREF(callable);
  781. cm->cm_callable = callable;
  782. }
  783. return (PyObject *)cm;
  784. }
  785. /* Static method object */
  786. /* A static method does not receive an implicit first argument.
  787. To declare a static method, use this idiom:
  788. class C:
  789. @staticmethod
  790. def f(arg1, arg2, ...):
  791. ...
  792. It can be called either on the class (e.g. C.f()) or on an instance
  793. (e.g. C().f()). Both the class and the instance are ignored, and
  794. neither is passed implicitly as the first argument to the method.
  795. Static methods in Python are similar to those found in Java or C++.
  796. For a more advanced concept, see class methods above.
  797. */
  798. typedef struct {
  799. PyObject_HEAD
  800. PyObject *sm_callable;
  801. PyObject *sm_dict;
  802. } staticmethod;
  803. static void
  804. sm_dealloc(staticmethod *sm)
  805. {
  806. _PyObject_GC_UNTRACK((PyObject *)sm);
  807. Py_XDECREF(sm->sm_callable);
  808. Py_XDECREF(sm->sm_dict);
  809. Py_TYPE(sm)->tp_free((PyObject *)sm);
  810. }
  811. static int
  812. sm_traverse(staticmethod *sm, visitproc visit, void *arg)
  813. {
  814. Py_VISIT(sm->sm_callable);
  815. Py_VISIT(sm->sm_dict);
  816. return 0;
  817. }
  818. static int
  819. sm_clear(staticmethod *sm)
  820. {
  821. Py_CLEAR(sm->sm_callable);
  822. Py_CLEAR(sm->sm_dict);
  823. return 0;
  824. }
  825. static PyObject *
  826. sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
  827. {
  828. staticmethod *sm = (staticmethod *)self;
  829. if (sm->sm_callable == NULL) {
  830. PyErr_SetString(PyExc_RuntimeError,
  831. "uninitialized staticmethod object");
  832. return NULL;
  833. }
  834. Py_INCREF(sm->sm_callable);
  835. return sm->sm_callable;
  836. }
  837. static int
  838. sm_init(PyObject *self, PyObject *args, PyObject *kwds)
  839. {
  840. staticmethod *sm = (staticmethod *)self;
  841. PyObject *callable;
  842. if (!_PyArg_NoKeywords("staticmethod", kwds))
  843. return -1;
  844. if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable))
  845. return -1;
  846. Py_INCREF(callable);
  847. Py_XSETREF(sm->sm_callable, callable);
  848. return 0;
  849. }
  850. static PyMemberDef sm_memberlist[] = {
  851. {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY},
  852. {NULL} /* Sentinel */
  853. };
  854. static PyObject *
  855. sm_get___isabstractmethod__(staticmethod *sm, void *closure)
  856. {
  857. int res = _PyObject_IsAbstract(sm->sm_callable);
  858. if (res == -1) {
  859. return NULL;
  860. }
  861. else if (res) {
  862. Py_RETURN_TRUE;
  863. }
  864. Py_RETURN_FALSE;
  865. }
  866. static PyGetSetDef sm_getsetlist[] = {
  867. {"__isabstractmethod__",
  868. (getter)sm_get___isabstractmethod__, NULL,
  869. NULL,
  870. NULL},
  871. {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
  872. {NULL} /* Sentinel */
  873. };
  874. PyDoc_STRVAR(staticmethod_doc,
  875. "staticmethod(function) -> method\n\
  876. \n\
  877. Convert a function to be a static method.\n\
  878. \n\
  879. A static method does not receive an implicit first argument.\n\
  880. To declare a static method, use this idiom:\n\
  881. \n\
  882. class C:\n\
  883. @staticmethod\n\
  884. def f(arg1, arg2, ...):\n\
  885. ...\n\
  886. \n\
  887. It can be called either on the class (e.g. C.f()) or on an instance\n\
  888. (e.g. C().f()). Both the class and the instance are ignored, and\n\
  889. neither is passed implicitly as the first argument to the method.\n\
  890. \n\
  891. Static methods in Python are similar to those found in Java or C++.\n\
  892. For a more advanced concept, see the classmethod builtin.");
  893. PyTypeObject PyStaticMethod_Type = {
  894. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  895. "staticmethod",
  896. sizeof(staticmethod),
  897. 0,
  898. (destructor)sm_dealloc, /* tp_dealloc */
  899. 0, /* tp_vectorcall_offset */
  900. 0, /* tp_getattr */
  901. 0, /* tp_setattr */
  902. 0, /* tp_as_async */
  903. 0, /* tp_repr */
  904. 0, /* tp_as_number */
  905. 0, /* tp_as_sequence */
  906. 0, /* tp_as_mapping */
  907. 0, /* tp_hash */
  908. 0, /* tp_call */
  909. 0, /* tp_str */
  910. 0, /* tp_getattro */
  911. 0, /* tp_setattro */
  912. 0, /* tp_as_buffer */
  913. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
  914. staticmethod_doc, /* tp_doc */
  915. (traverseproc)sm_traverse, /* tp_traverse */
  916. (inquiry)sm_clear, /* tp_clear */
  917. 0, /* tp_richcompare */
  918. 0, /* tp_weaklistoffset */
  919. 0, /* tp_iter */
  920. 0, /* tp_iternext */
  921. 0, /* tp_methods */
  922. sm_memberlist, /* tp_members */
  923. sm_getsetlist, /* tp_getset */
  924. 0, /* tp_base */
  925. 0, /* tp_dict */
  926. sm_descr_get, /* tp_descr_get */
  927. 0, /* tp_descr_set */
  928. offsetof(staticmethod, sm_dict), /* tp_dictoffset */
  929. sm_init, /* tp_init */
  930. PyType_GenericAlloc, /* tp_alloc */
  931. PyType_GenericNew, /* tp_new */
  932. PyObject_GC_Del, /* tp_free */
  933. };
  934. PyObject *
  935. PyStaticMethod_New(PyObject *callable)
  936. {
  937. staticmethod *sm = (staticmethod *)
  938. PyType_GenericAlloc(&PyStaticMethod_Type, 0);
  939. if (sm != NULL) {
  940. Py_INCREF(callable);
  941. sm->sm_callable = callable;
  942. }
  943. return (PyObject *)sm;
  944. }