/Objects/funcobject.c

http://unladen-swallow.googlecode.com/ · C · 892 lines · 758 code · 78 blank · 56 comment · 117 complexity · aedb33ea774ac1483a0d101a77ffbfb0 MD5 · raw file

  1. /* Function object implementation */
  2. #include "Python.h"
  3. #include "code.h"
  4. #include "eval.h"
  5. #include "structmember.h"
  6. PyObject *
  7. PyFunction_New(PyObject *code, PyObject *globals)
  8. {
  9. PyFunctionObject *op = PyObject_GC_New(PyFunctionObject,
  10. &PyFunction_Type);
  11. static PyObject *__name__ = 0;
  12. if (op != NULL) {
  13. PyObject *doc;
  14. PyObject *consts;
  15. PyObject *module;
  16. op->func_weakreflist = NULL;
  17. Py_INCREF(code);
  18. op->func_code = code;
  19. Py_INCREF(globals);
  20. op->func_globals = globals;
  21. op->func_name = ((PyCodeObject *)code)->co_name;
  22. Py_INCREF(op->func_name);
  23. op->func_defaults = NULL; /* No default arguments */
  24. op->func_closure = NULL;
  25. consts = ((PyCodeObject *)code)->co_consts;
  26. if (PyTuple_Size(consts) >= 1) {
  27. doc = PyTuple_GetItem(consts, 0);
  28. if (!PyString_Check(doc) && !PyUnicode_Check(doc))
  29. doc = Py_None;
  30. }
  31. else
  32. doc = Py_None;
  33. Py_INCREF(doc);
  34. op->func_doc = doc;
  35. op->func_dict = NULL;
  36. op->func_module = NULL;
  37. /* __module__: If module name is in globals, use it.
  38. Otherwise, use None.
  39. */
  40. if (!__name__) {
  41. __name__ = PyString_InternFromString("__name__");
  42. if (!__name__) {
  43. Py_DECREF(op);
  44. return NULL;
  45. }
  46. }
  47. module = PyDict_GetItem(globals, __name__);
  48. if (module) {
  49. Py_INCREF(module);
  50. op->func_module = module;
  51. }
  52. }
  53. else
  54. return NULL;
  55. _PyObject_GC_TRACK(op);
  56. return (PyObject *)op;
  57. }
  58. PyObject *
  59. PyFunction_GetCode(PyObject *op)
  60. {
  61. if (!PyFunction_Check(op)) {
  62. PyErr_BadInternalCall();
  63. return NULL;
  64. }
  65. return ((PyFunctionObject *) op) -> func_code;
  66. }
  67. PyObject *
  68. PyFunction_GetGlobals(PyObject *op)
  69. {
  70. if (!PyFunction_Check(op)) {
  71. PyErr_BadInternalCall();
  72. return NULL;
  73. }
  74. return ((PyFunctionObject *) op) -> func_globals;
  75. }
  76. PyObject *
  77. PyFunction_GetModule(PyObject *op)
  78. {
  79. if (!PyFunction_Check(op)) {
  80. PyErr_BadInternalCall();
  81. return NULL;
  82. }
  83. return ((PyFunctionObject *) op) -> func_module;
  84. }
  85. PyObject *
  86. PyFunction_GetDefaults(PyObject *op)
  87. {
  88. if (!PyFunction_Check(op)) {
  89. PyErr_BadInternalCall();
  90. return NULL;
  91. }
  92. return ((PyFunctionObject *) op) -> func_defaults;
  93. }
  94. int
  95. PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
  96. {
  97. if (!PyFunction_Check(op)) {
  98. PyErr_BadInternalCall();
  99. return -1;
  100. }
  101. if (defaults == Py_None)
  102. defaults = NULL;
  103. else if (defaults && PyTuple_Check(defaults)) {
  104. Py_INCREF(defaults);
  105. }
  106. else {
  107. PyErr_SetString(PyExc_SystemError, "non-tuple default args");
  108. return -1;
  109. }
  110. Py_XDECREF(((PyFunctionObject *) op) -> func_defaults);
  111. ((PyFunctionObject *) op) -> func_defaults = defaults;
  112. return 0;
  113. }
  114. PyObject *
  115. PyFunction_GetClosure(PyObject *op)
  116. {
  117. if (!PyFunction_Check(op)) {
  118. PyErr_BadInternalCall();
  119. return NULL;
  120. }
  121. return ((PyFunctionObject *) op) -> func_closure;
  122. }
  123. int
  124. PyFunction_SetClosure(PyObject *op, PyObject *closure)
  125. {
  126. if (!PyFunction_Check(op)) {
  127. PyErr_BadInternalCall();
  128. return -1;
  129. }
  130. if (closure == Py_None)
  131. closure = NULL;
  132. else if (PyTuple_Check(closure)) {
  133. Py_INCREF(closure);
  134. }
  135. else {
  136. PyErr_Format(PyExc_SystemError,
  137. "expected tuple for closure, got '%.100s'",
  138. closure->ob_type->tp_name);
  139. return -1;
  140. }
  141. Py_XDECREF(((PyFunctionObject *) op) -> func_closure);
  142. ((PyFunctionObject *) op) -> func_closure = closure;
  143. return 0;
  144. }
  145. /* Methods */
  146. #define OFF(x) offsetof(PyFunctionObject, x)
  147. static PyMemberDef func_memberlist[] = {
  148. {"func_closure", T_OBJECT, OFF(func_closure),
  149. RESTRICTED|READONLY},
  150. {"__closure__", T_OBJECT, OFF(func_closure),
  151. RESTRICTED|READONLY},
  152. {"func_doc", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED},
  153. {"__doc__", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED},
  154. {"func_globals", T_OBJECT, OFF(func_globals),
  155. RESTRICTED|READONLY},
  156. {"__globals__", T_OBJECT, OFF(func_globals),
  157. RESTRICTED|READONLY},
  158. {"__module__", T_OBJECT, OFF(func_module), PY_WRITE_RESTRICTED},
  159. {NULL} /* Sentinel */
  160. };
  161. static int
  162. restricted(void)
  163. {
  164. if (!PyEval_GetRestricted())
  165. return 0;
  166. PyErr_SetString(PyExc_RuntimeError,
  167. "function attributes not accessible in restricted mode");
  168. return 1;
  169. }
  170. static PyObject *
  171. func_get_dict(PyFunctionObject *op)
  172. {
  173. if (restricted())
  174. return NULL;
  175. if (op->func_dict == NULL) {
  176. op->func_dict = PyDict_New();
  177. if (op->func_dict == NULL)
  178. return NULL;
  179. }
  180. Py_INCREF(op->func_dict);
  181. return op->func_dict;
  182. }
  183. static int
  184. func_set_dict(PyFunctionObject *op, PyObject *value)
  185. {
  186. PyObject *tmp;
  187. if (restricted())
  188. return -1;
  189. /* It is illegal to del f.func_dict */
  190. if (value == NULL) {
  191. PyErr_SetString(PyExc_TypeError,
  192. "function's dictionary may not be deleted");
  193. return -1;
  194. }
  195. /* Can only set func_dict to a dictionary */
  196. if (!PyDict_Check(value)) {
  197. PyErr_SetString(PyExc_TypeError,
  198. "setting function's dictionary to a non-dict");
  199. return -1;
  200. }
  201. tmp = op->func_dict;
  202. Py_INCREF(value);
  203. op->func_dict = value;
  204. Py_XDECREF(tmp);
  205. return 0;
  206. }
  207. static PyObject *
  208. func_get_code(PyFunctionObject *op)
  209. {
  210. if (restricted())
  211. return NULL;
  212. Py_INCREF(op->func_code);
  213. return op->func_code;
  214. }
  215. static int
  216. func_set_code(PyFunctionObject *op, PyObject *value)
  217. {
  218. PyObject *tmp;
  219. Py_ssize_t nfree, nclosure;
  220. if (restricted())
  221. return -1;
  222. /* Not legal to del f.func_code or to set it to anything
  223. * other than a code object. */
  224. if (value == NULL || !PyCode_Check(value)) {
  225. PyErr_SetString(PyExc_TypeError,
  226. "__code__ must be set to a code object");
  227. return -1;
  228. }
  229. nfree = PyCode_GetNumFree((PyCodeObject *)value);
  230. nclosure = (op->func_closure == NULL ? 0 :
  231. PyTuple_GET_SIZE(op->func_closure));
  232. if (nclosure != nfree) {
  233. PyErr_Format(PyExc_ValueError,
  234. "%s() requires a code object with %zd free vars,"
  235. " not %zd",
  236. PyString_AsString(op->func_name),
  237. nclosure, nfree);
  238. return -1;
  239. }
  240. tmp = op->func_code;
  241. Py_INCREF(value);
  242. op->func_code = value;
  243. Py_DECREF(tmp);
  244. return 0;
  245. }
  246. static PyObject *
  247. func_get_name(PyFunctionObject *op)
  248. {
  249. Py_INCREF(op->func_name);
  250. return op->func_name;
  251. }
  252. static int
  253. func_set_name(PyFunctionObject *op, PyObject *value)
  254. {
  255. PyObject *tmp;
  256. if (restricted())
  257. return -1;
  258. /* Not legal to del f.func_name or to set it to anything
  259. * other than a string object. */
  260. if (value == NULL || !PyString_Check(value)) {
  261. PyErr_SetString(PyExc_TypeError,
  262. "__name__ must be set to a string object");
  263. return -1;
  264. }
  265. tmp = op->func_name;
  266. Py_INCREF(value);
  267. op->func_name = value;
  268. Py_DECREF(tmp);
  269. return 0;
  270. }
  271. static PyObject *
  272. func_get_defaults(PyFunctionObject *op)
  273. {
  274. if (restricted())
  275. return NULL;
  276. if (op->func_defaults == NULL) {
  277. Py_INCREF(Py_None);
  278. return Py_None;
  279. }
  280. Py_INCREF(op->func_defaults);
  281. return op->func_defaults;
  282. }
  283. static int
  284. func_set_defaults(PyFunctionObject *op, PyObject *value)
  285. {
  286. PyObject *tmp;
  287. if (restricted())
  288. return -1;
  289. /* Legal to del f.func_defaults.
  290. * Can only set func_defaults to NULL or a tuple. */
  291. if (value == Py_None)
  292. value = NULL;
  293. if (value != NULL && !PyTuple_Check(value)) {
  294. PyErr_SetString(PyExc_TypeError,
  295. "__defaults__ must be set to a tuple object");
  296. return -1;
  297. }
  298. tmp = op->func_defaults;
  299. Py_XINCREF(value);
  300. op->func_defaults = value;
  301. Py_XDECREF(tmp);
  302. return 0;
  303. }
  304. static PyGetSetDef func_getsetlist[] = {
  305. {"func_code", (getter)func_get_code, (setter)func_set_code},
  306. {"__code__", (getter)func_get_code, (setter)func_set_code},
  307. {"func_defaults", (getter)func_get_defaults,
  308. (setter)func_set_defaults},
  309. {"__defaults__", (getter)func_get_defaults,
  310. (setter)func_set_defaults},
  311. {"func_dict", (getter)func_get_dict, (setter)func_set_dict},
  312. {"__dict__", (getter)func_get_dict, (setter)func_set_dict},
  313. {"func_name", (getter)func_get_name, (setter)func_set_name},
  314. {"__name__", (getter)func_get_name, (setter)func_set_name},
  315. {NULL} /* Sentinel */
  316. };
  317. PyDoc_STRVAR(func_doc,
  318. "function(code, globals[, name[, argdefs[, closure]]])\n\
  319. \n\
  320. Create a function object from a code object and a dictionary.\n\
  321. The optional name string overrides the name from the code object.\n\
  322. The optional argdefs tuple specifies the default argument values.\n\
  323. The optional closure tuple supplies the bindings for free variables.");
  324. /* func_new() maintains the following invariants for closures. The
  325. closure must correspond to the free variables of the code object.
  326. if len(code.co_freevars) == 0:
  327. closure = NULL
  328. else:
  329. len(closure) == len(code.co_freevars)
  330. for every elt in closure, type(elt) == cell
  331. */
  332. static PyObject *
  333. func_new(PyTypeObject* type, PyObject* args, PyObject* kw)
  334. {
  335. PyCodeObject *code;
  336. PyObject *globals;
  337. PyObject *name = Py_None;
  338. PyObject *defaults = Py_None;
  339. PyObject *closure = Py_None;
  340. PyFunctionObject *newfunc;
  341. Py_ssize_t nfree, nclosure;
  342. static char *kwlist[] = {"code", "globals", "name",
  343. "argdefs", "closure", 0};
  344. if (!PyArg_ParseTupleAndKeywords(args, kw, "O!O!|OOO:function",
  345. kwlist,
  346. &PyCode_Type, &code,
  347. &PyDict_Type, &globals,
  348. &name, &defaults, &closure))
  349. return NULL;
  350. if (name != Py_None && !PyString_Check(name)) {
  351. PyErr_SetString(PyExc_TypeError,
  352. "arg 3 (name) must be None or string");
  353. return NULL;
  354. }
  355. if (defaults != Py_None && !PyTuple_Check(defaults)) {
  356. PyErr_SetString(PyExc_TypeError,
  357. "arg 4 (defaults) must be None or tuple");
  358. return NULL;
  359. }
  360. nfree = PyTuple_GET_SIZE(code->co_freevars);
  361. if (!PyTuple_Check(closure)) {
  362. if (nfree && closure == Py_None) {
  363. PyErr_SetString(PyExc_TypeError,
  364. "arg 5 (closure) must be tuple");
  365. return NULL;
  366. }
  367. else if (closure != Py_None) {
  368. PyErr_SetString(PyExc_TypeError,
  369. "arg 5 (closure) must be None or tuple");
  370. return NULL;
  371. }
  372. }
  373. /* check that the closure is well-formed */
  374. nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
  375. if (nfree != nclosure)
  376. return PyErr_Format(PyExc_ValueError,
  377. "%s requires closure of length %zd, not %zd",
  378. PyString_AS_STRING(code->co_name),
  379. nfree, nclosure);
  380. if (nclosure) {
  381. Py_ssize_t i;
  382. for (i = 0; i < nclosure; i++) {
  383. PyObject *o = PyTuple_GET_ITEM(closure, i);
  384. if (!PyCell_Check(o)) {
  385. return PyErr_Format(PyExc_TypeError,
  386. "arg 5 (closure) expected cell, found %s",
  387. o->ob_type->tp_name);
  388. }
  389. }
  390. }
  391. newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
  392. globals);
  393. if (newfunc == NULL)
  394. return NULL;
  395. if (name != Py_None) {
  396. Py_INCREF(name);
  397. Py_DECREF(newfunc->func_name);
  398. newfunc->func_name = name;
  399. }
  400. if (defaults != Py_None) {
  401. Py_INCREF(defaults);
  402. newfunc->func_defaults = defaults;
  403. }
  404. if (closure != Py_None) {
  405. Py_INCREF(closure);
  406. newfunc->func_closure = closure;
  407. }
  408. return (PyObject *)newfunc;
  409. }
  410. static void
  411. func_dealloc(PyFunctionObject *op)
  412. {
  413. _PyObject_GC_UNTRACK(op);
  414. if (op->func_weakreflist != NULL)
  415. PyObject_ClearWeakRefs((PyObject *) op);
  416. Py_DECREF(op->func_code);
  417. Py_DECREF(op->func_globals);
  418. Py_XDECREF(op->func_module);
  419. Py_DECREF(op->func_name);
  420. Py_XDECREF(op->func_defaults);
  421. Py_XDECREF(op->func_doc);
  422. Py_XDECREF(op->func_dict);
  423. Py_XDECREF(op->func_closure);
  424. PyObject_GC_Del(op);
  425. }
  426. static PyObject*
  427. func_repr(PyFunctionObject *op)
  428. {
  429. return PyString_FromFormat("<function %s at %p>",
  430. PyString_AsString(op->func_name),
  431. op);
  432. }
  433. static int
  434. func_traverse(PyFunctionObject *f, visitproc visit, void *arg)
  435. {
  436. Py_VISIT(f->func_code);
  437. Py_VISIT(f->func_globals);
  438. Py_VISIT(f->func_module);
  439. Py_VISIT(f->func_defaults);
  440. Py_VISIT(f->func_doc);
  441. Py_VISIT(f->func_name);
  442. Py_VISIT(f->func_dict);
  443. Py_VISIT(f->func_closure);
  444. return 0;
  445. }
  446. static PyObject *
  447. function_call(PyObject *func, PyObject *arg, PyObject *kw)
  448. {
  449. PyObject *result;
  450. PyObject *argdefs;
  451. PyObject **d, **k;
  452. Py_ssize_t nk, nd;
  453. argdefs = PyFunction_GET_DEFAULTS(func);
  454. if (argdefs != NULL && PyTuple_Check(argdefs)) {
  455. d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0);
  456. nd = PyTuple_Size(argdefs);
  457. }
  458. else {
  459. d = NULL;
  460. nd = 0;
  461. }
  462. if (kw != NULL && PyDict_Check(kw)) {
  463. Py_ssize_t pos, i;
  464. nk = PyDict_Size(kw);
  465. k = PyMem_NEW(PyObject *, 2*nk);
  466. if (k == NULL) {
  467. PyErr_NoMemory();
  468. return NULL;
  469. }
  470. pos = i = 0;
  471. while (PyDict_Next(kw, &pos, &k[i], &k[i+1]))
  472. i += 2;
  473. nk = i/2;
  474. /* XXX This is broken if the caller deletes dict items! */
  475. }
  476. else {
  477. k = NULL;
  478. nk = 0;
  479. }
  480. result = PyEval_EvalCodeEx(
  481. (PyCodeObject *)PyFunction_GET_CODE(func),
  482. PyFunction_GET_GLOBALS(func), (PyObject *)NULL,
  483. &PyTuple_GET_ITEM(arg, 0), PyTuple_Size(arg),
  484. k, nk, d, nd,
  485. PyFunction_GET_CLOSURE(func));
  486. if (k != NULL)
  487. PyMem_DEL(k);
  488. return result;
  489. }
  490. /* Bind a function to an object */
  491. static PyObject *
  492. func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
  493. {
  494. if (obj == Py_None)
  495. obj = NULL;
  496. return PyMethod_New(func, obj, type);
  497. }
  498. PyTypeObject PyFunction_Type = {
  499. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  500. "function",
  501. sizeof(PyFunctionObject),
  502. 0,
  503. (destructor)func_dealloc, /* tp_dealloc */
  504. 0, /* tp_print */
  505. 0, /* tp_getattr */
  506. 0, /* tp_setattr */
  507. 0, /* tp_compare */
  508. (reprfunc)func_repr, /* tp_repr */
  509. 0, /* tp_as_number */
  510. 0, /* tp_as_sequence */
  511. 0, /* tp_as_mapping */
  512. 0, /* tp_hash */
  513. function_call, /* tp_call */
  514. 0, /* tp_str */
  515. PyObject_GenericGetAttr, /* tp_getattro */
  516. PyObject_GenericSetAttr, /* tp_setattro */
  517. 0, /* tp_as_buffer */
  518. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  519. func_doc, /* tp_doc */
  520. (traverseproc)func_traverse, /* tp_traverse */
  521. 0, /* tp_clear */
  522. 0, /* tp_richcompare */
  523. offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
  524. 0, /* tp_iter */
  525. 0, /* tp_iternext */
  526. 0, /* tp_methods */
  527. func_memberlist, /* tp_members */
  528. func_getsetlist, /* tp_getset */
  529. 0, /* tp_base */
  530. 0, /* tp_dict */
  531. func_descr_get, /* tp_descr_get */
  532. 0, /* tp_descr_set */
  533. offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */
  534. 0, /* tp_init */
  535. 0, /* tp_alloc */
  536. func_new, /* tp_new */
  537. };
  538. /* Class method object */
  539. /* A class method receives the class as implicit first argument,
  540. just like an instance method receives the instance.
  541. To declare a class method, use this idiom:
  542. class C:
  543. def f(cls, arg1, arg2, ...): ...
  544. f = classmethod(f)
  545. It can be called either on the class (e.g. C.f()) or on an instance
  546. (e.g. C().f()); the instance is ignored except for its class.
  547. If a class method is called for a derived class, the derived class
  548. object is passed as the implied first argument.
  549. Class methods are different than C++ or Java static methods.
  550. If you want those, see static methods below.
  551. */
  552. typedef struct {
  553. PyObject_HEAD
  554. PyObject *cm_callable;
  555. } classmethod;
  556. static void
  557. cm_dealloc(classmethod *cm)
  558. {
  559. _PyObject_GC_UNTRACK((PyObject *)cm);
  560. Py_XDECREF(cm->cm_callable);
  561. Py_TYPE(cm)->tp_free((PyObject *)cm);
  562. }
  563. static int
  564. cm_traverse(classmethod *cm, visitproc visit, void *arg)
  565. {
  566. Py_VISIT(cm->cm_callable);
  567. return 0;
  568. }
  569. static int
  570. cm_clear(classmethod *cm)
  571. {
  572. Py_CLEAR(cm->cm_callable);
  573. return 0;
  574. }
  575. static PyObject *
  576. cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
  577. {
  578. classmethod *cm = (classmethod *)self;
  579. if (cm->cm_callable == NULL) {
  580. PyErr_SetString(PyExc_RuntimeError,
  581. "uninitialized classmethod object");
  582. return NULL;
  583. }
  584. if (type == NULL)
  585. type = (PyObject *)(Py_TYPE(obj));
  586. return PyMethod_New(cm->cm_callable,
  587. type, (PyObject *)(Py_TYPE(type)));
  588. }
  589. static int
  590. cm_init(PyObject *self, PyObject *args, PyObject *kwds)
  591. {
  592. classmethod *cm = (classmethod *)self;
  593. PyObject *callable;
  594. if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable))
  595. return -1;
  596. if (!_PyArg_NoKeywords("classmethod", kwds))
  597. return -1;
  598. if (!PyCallable_Check(callable)) {
  599. PyErr_Format(PyExc_TypeError, "'%s' object is not callable",
  600. callable->ob_type->tp_name);
  601. return -1;
  602. }
  603. Py_INCREF(callable);
  604. cm->cm_callable = callable;
  605. return 0;
  606. }
  607. PyDoc_STRVAR(classmethod_doc,
  608. "classmethod(function) -> method\n\
  609. \n\
  610. Convert a function to be a class method.\n\
  611. \n\
  612. A class method receives the class as implicit first argument,\n\
  613. just like an instance method receives the instance.\n\
  614. To declare a class method, use this idiom:\n\
  615. \n\
  616. class C:\n\
  617. def f(cls, arg1, arg2, ...): ...\n\
  618. f = classmethod(f)\n\
  619. \n\
  620. It can be called either on the class (e.g. C.f()) or on an instance\n\
  621. (e.g. C().f()). The instance is ignored except for its class.\n\
  622. If a class method is called for a derived class, the derived class\n\
  623. object is passed as the implied first argument.\n\
  624. \n\
  625. Class methods are different than C++ or Java static methods.\n\
  626. If you want those, see the staticmethod builtin.");
  627. PyTypeObject PyClassMethod_Type = {
  628. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  629. "classmethod",
  630. sizeof(classmethod),
  631. 0,
  632. (destructor)cm_dealloc, /* tp_dealloc */
  633. 0, /* tp_print */
  634. 0, /* tp_getattr */
  635. 0, /* tp_setattr */
  636. 0, /* tp_compare */
  637. 0, /* tp_repr */
  638. 0, /* tp_as_number */
  639. 0, /* tp_as_sequence */
  640. 0, /* tp_as_mapping */
  641. 0, /* tp_hash */
  642. 0, /* tp_call */
  643. 0, /* tp_str */
  644. PyObject_GenericGetAttr, /* tp_getattro */
  645. 0, /* tp_setattro */
  646. 0, /* tp_as_buffer */
  647. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
  648. classmethod_doc, /* tp_doc */
  649. (traverseproc)cm_traverse, /* tp_traverse */
  650. (inquiry)cm_clear, /* tp_clear */
  651. 0, /* tp_richcompare */
  652. 0, /* tp_weaklistoffset */
  653. 0, /* tp_iter */
  654. 0, /* tp_iternext */
  655. 0, /* tp_methods */
  656. 0, /* tp_members */
  657. 0, /* tp_getset */
  658. 0, /* tp_base */
  659. 0, /* tp_dict */
  660. cm_descr_get, /* tp_descr_get */
  661. 0, /* tp_descr_set */
  662. 0, /* tp_dictoffset */
  663. cm_init, /* tp_init */
  664. PyType_GenericAlloc, /* tp_alloc */
  665. PyType_GenericNew, /* tp_new */
  666. PyObject_GC_Del, /* tp_free */
  667. };
  668. PyObject *
  669. PyClassMethod_New(PyObject *callable)
  670. {
  671. classmethod *cm = (classmethod *)
  672. PyType_GenericAlloc(&PyClassMethod_Type, 0);
  673. if (cm != NULL) {
  674. Py_INCREF(callable);
  675. cm->cm_callable = callable;
  676. }
  677. return (PyObject *)cm;
  678. }
  679. /* Static method object */
  680. /* A static method does not receive an implicit first argument.
  681. To declare a static method, use this idiom:
  682. class C:
  683. def f(arg1, arg2, ...): ...
  684. f = staticmethod(f)
  685. It can be called either on the class (e.g. C.f()) or on an instance
  686. (e.g. C().f()); the instance is ignored except for its class.
  687. Static methods in Python are similar to those found in Java or C++.
  688. For a more advanced concept, see class methods above.
  689. */
  690. typedef struct {
  691. PyObject_HEAD
  692. PyObject *sm_callable;
  693. } staticmethod;
  694. static void
  695. sm_dealloc(staticmethod *sm)
  696. {
  697. _PyObject_GC_UNTRACK((PyObject *)sm);
  698. Py_XDECREF(sm->sm_callable);
  699. Py_TYPE(sm)->tp_free((PyObject *)sm);
  700. }
  701. static int
  702. sm_traverse(staticmethod *sm, visitproc visit, void *arg)
  703. {
  704. Py_VISIT(sm->sm_callable);
  705. return 0;
  706. }
  707. static int
  708. sm_clear(staticmethod *sm)
  709. {
  710. Py_XDECREF(sm->sm_callable);
  711. sm->sm_callable = NULL;
  712. return 0;
  713. }
  714. static PyObject *
  715. sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
  716. {
  717. staticmethod *sm = (staticmethod *)self;
  718. if (sm->sm_callable == NULL) {
  719. PyErr_SetString(PyExc_RuntimeError,
  720. "uninitialized staticmethod object");
  721. return NULL;
  722. }
  723. Py_INCREF(sm->sm_callable);
  724. return sm->sm_callable;
  725. }
  726. static int
  727. sm_init(PyObject *self, PyObject *args, PyObject *kwds)
  728. {
  729. staticmethod *sm = (staticmethod *)self;
  730. PyObject *callable;
  731. if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable))
  732. return -1;
  733. if (!_PyArg_NoKeywords("staticmethod", kwds))
  734. return -1;
  735. Py_INCREF(callable);
  736. sm->sm_callable = callable;
  737. return 0;
  738. }
  739. PyDoc_STRVAR(staticmethod_doc,
  740. "staticmethod(function) -> method\n\
  741. \n\
  742. Convert a function to be a static method.\n\
  743. \n\
  744. A static method does not receive an implicit first argument.\n\
  745. To declare a static method, use this idiom:\n\
  746. \n\
  747. class C:\n\
  748. def f(arg1, arg2, ...): ...\n\
  749. f = staticmethod(f)\n\
  750. \n\
  751. It can be called either on the class (e.g. C.f()) or on an instance\n\
  752. (e.g. C().f()). The instance is ignored except for its class.\n\
  753. \n\
  754. Static methods in Python are similar to those found in Java or C++.\n\
  755. For a more advanced concept, see the classmethod builtin.");
  756. PyTypeObject PyStaticMethod_Type = {
  757. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  758. "staticmethod",
  759. sizeof(staticmethod),
  760. 0,
  761. (destructor)sm_dealloc, /* tp_dealloc */
  762. 0, /* tp_print */
  763. 0, /* tp_getattr */
  764. 0, /* tp_setattr */
  765. 0, /* tp_compare */
  766. 0, /* tp_repr */
  767. 0, /* tp_as_number */
  768. 0, /* tp_as_sequence */
  769. 0, /* tp_as_mapping */
  770. 0, /* tp_hash */
  771. 0, /* tp_call */
  772. 0, /* tp_str */
  773. PyObject_GenericGetAttr, /* tp_getattro */
  774. 0, /* tp_setattro */
  775. 0, /* tp_as_buffer */
  776. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
  777. staticmethod_doc, /* tp_doc */
  778. (traverseproc)sm_traverse, /* tp_traverse */
  779. (inquiry)sm_clear, /* tp_clear */
  780. 0, /* tp_richcompare */
  781. 0, /* tp_weaklistoffset */
  782. 0, /* tp_iter */
  783. 0, /* tp_iternext */
  784. 0, /* tp_methods */
  785. 0, /* tp_members */
  786. 0, /* tp_getset */
  787. 0, /* tp_base */
  788. 0, /* tp_dict */
  789. sm_descr_get, /* tp_descr_get */
  790. 0, /* tp_descr_set */
  791. 0, /* tp_dictoffset */
  792. sm_init, /* tp_init */
  793. PyType_GenericAlloc, /* tp_alloc */
  794. PyType_GenericNew, /* tp_new */
  795. PyObject_GC_Del, /* tp_free */
  796. };
  797. PyObject *
  798. PyStaticMethod_New(PyObject *callable)
  799. {
  800. staticmethod *sm = (staticmethod *)
  801. PyType_GenericAlloc(&PyStaticMethod_Type, 0);
  802. if (sm != NULL) {
  803. Py_INCREF(callable);
  804. sm->sm_callable = callable;
  805. }
  806. return (PyObject *)sm;
  807. }