- Issue #6624: yArg_ParseTuple with "s" format when parsing argument with
[python.git] / Objects / funcobject.c
blob7774e6d1e5e2baa6ecbe039632281f405a9bec98
2 /* Function object implementation */
4 #include "Python.h"
5 #include "code.h"
6 #include "eval.h"
7 #include "structmember.h"
9 PyObject *
10 PyFunction_New(PyObject *code, PyObject *globals)
12 PyFunctionObject *op = PyObject_GC_New(PyFunctionObject,
13 &PyFunction_Type);
14 static PyObject *__name__ = 0;
15 if (op != NULL) {
16 PyObject *doc;
17 PyObject *consts;
18 PyObject *module;
19 op->func_weakreflist = NULL;
20 Py_INCREF(code);
21 op->func_code = code;
22 Py_INCREF(globals);
23 op->func_globals = globals;
24 op->func_name = ((PyCodeObject *)code)->co_name;
25 Py_INCREF(op->func_name);
26 op->func_defaults = NULL; /* No default arguments */
27 op->func_closure = NULL;
28 consts = ((PyCodeObject *)code)->co_consts;
29 if (PyTuple_Size(consts) >= 1) {
30 doc = PyTuple_GetItem(consts, 0);
31 if (!PyString_Check(doc) && !PyUnicode_Check(doc))
32 doc = Py_None;
34 else
35 doc = Py_None;
36 Py_INCREF(doc);
37 op->func_doc = doc;
38 op->func_dict = NULL;
39 op->func_module = NULL;
41 /* __module__: If module name is in globals, use it.
42 Otherwise, use None.
44 if (!__name__) {
45 __name__ = PyString_InternFromString("__name__");
46 if (!__name__) {
47 Py_DECREF(op);
48 return NULL;
51 module = PyDict_GetItem(globals, __name__);
52 if (module) {
53 Py_INCREF(module);
54 op->func_module = module;
57 else
58 return NULL;
59 _PyObject_GC_TRACK(op);
60 return (PyObject *)op;
63 PyObject *
64 PyFunction_GetCode(PyObject *op)
66 if (!PyFunction_Check(op)) {
67 PyErr_BadInternalCall();
68 return NULL;
70 return ((PyFunctionObject *) op) -> func_code;
73 PyObject *
74 PyFunction_GetGlobals(PyObject *op)
76 if (!PyFunction_Check(op)) {
77 PyErr_BadInternalCall();
78 return NULL;
80 return ((PyFunctionObject *) op) -> func_globals;
83 PyObject *
84 PyFunction_GetModule(PyObject *op)
86 if (!PyFunction_Check(op)) {
87 PyErr_BadInternalCall();
88 return NULL;
90 return ((PyFunctionObject *) op) -> func_module;
93 PyObject *
94 PyFunction_GetDefaults(PyObject *op)
96 if (!PyFunction_Check(op)) {
97 PyErr_BadInternalCall();
98 return NULL;
100 return ((PyFunctionObject *) op) -> func_defaults;
104 PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
106 if (!PyFunction_Check(op)) {
107 PyErr_BadInternalCall();
108 return -1;
110 if (defaults == Py_None)
111 defaults = NULL;
112 else if (defaults && PyTuple_Check(defaults)) {
113 Py_INCREF(defaults);
115 else {
116 PyErr_SetString(PyExc_SystemError, "non-tuple default args");
117 return -1;
119 Py_XDECREF(((PyFunctionObject *) op) -> func_defaults);
120 ((PyFunctionObject *) op) -> func_defaults = defaults;
121 return 0;
124 PyObject *
125 PyFunction_GetClosure(PyObject *op)
127 if (!PyFunction_Check(op)) {
128 PyErr_BadInternalCall();
129 return NULL;
131 return ((PyFunctionObject *) op) -> func_closure;
135 PyFunction_SetClosure(PyObject *op, PyObject *closure)
137 if (!PyFunction_Check(op)) {
138 PyErr_BadInternalCall();
139 return -1;
141 if (closure == Py_None)
142 closure = NULL;
143 else if (PyTuple_Check(closure)) {
144 Py_INCREF(closure);
146 else {
147 PyErr_Format(PyExc_SystemError,
148 "expected tuple for closure, got '%.100s'",
149 closure->ob_type->tp_name);
150 return -1;
152 Py_XDECREF(((PyFunctionObject *) op) -> func_closure);
153 ((PyFunctionObject *) op) -> func_closure = closure;
154 return 0;
157 /* Methods */
159 #define OFF(x) offsetof(PyFunctionObject, x)
161 static PyMemberDef func_memberlist[] = {
162 {"func_closure", T_OBJECT, OFF(func_closure),
163 RESTRICTED|READONLY},
164 {"__closure__", T_OBJECT, OFF(func_closure),
165 RESTRICTED|READONLY},
166 {"func_doc", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED},
167 {"__doc__", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED},
168 {"func_globals", T_OBJECT, OFF(func_globals),
169 RESTRICTED|READONLY},
170 {"__globals__", T_OBJECT, OFF(func_globals),
171 RESTRICTED|READONLY},
172 {"__module__", T_OBJECT, OFF(func_module), PY_WRITE_RESTRICTED},
173 {NULL} /* Sentinel */
176 static int
177 restricted(void)
179 if (!PyEval_GetRestricted())
180 return 0;
181 PyErr_SetString(PyExc_RuntimeError,
182 "function attributes not accessible in restricted mode");
183 return 1;
186 static PyObject *
187 func_get_dict(PyFunctionObject *op)
189 if (restricted())
190 return NULL;
191 if (op->func_dict == NULL) {
192 op->func_dict = PyDict_New();
193 if (op->func_dict == NULL)
194 return NULL;
196 Py_INCREF(op->func_dict);
197 return op->func_dict;
200 static int
201 func_set_dict(PyFunctionObject *op, PyObject *value)
203 PyObject *tmp;
205 if (restricted())
206 return -1;
207 /* It is illegal to del f.func_dict */
208 if (value == NULL) {
209 PyErr_SetString(PyExc_TypeError,
210 "function's dictionary may not be deleted");
211 return -1;
213 /* Can only set func_dict to a dictionary */
214 if (!PyDict_Check(value)) {
215 PyErr_SetString(PyExc_TypeError,
216 "setting function's dictionary to a non-dict");
217 return -1;
219 tmp = op->func_dict;
220 Py_INCREF(value);
221 op->func_dict = value;
222 Py_XDECREF(tmp);
223 return 0;
226 static PyObject *
227 func_get_code(PyFunctionObject *op)
229 if (restricted())
230 return NULL;
231 Py_INCREF(op->func_code);
232 return op->func_code;
235 static int
236 func_set_code(PyFunctionObject *op, PyObject *value)
238 PyObject *tmp;
239 Py_ssize_t nfree, nclosure;
241 if (restricted())
242 return -1;
243 /* Not legal to del f.func_code or to set it to anything
244 * other than a code object. */
245 if (value == NULL || !PyCode_Check(value)) {
246 PyErr_SetString(PyExc_TypeError,
247 "__code__ must be set to a code object");
248 return -1;
250 nfree = PyCode_GetNumFree((PyCodeObject *)value);
251 nclosure = (op->func_closure == NULL ? 0 :
252 PyTuple_GET_SIZE(op->func_closure));
253 if (nclosure != nfree) {
254 PyErr_Format(PyExc_ValueError,
255 "%s() requires a code object with %zd free vars,"
256 " not %zd",
257 PyString_AsString(op->func_name),
258 nclosure, nfree);
259 return -1;
261 tmp = op->func_code;
262 Py_INCREF(value);
263 op->func_code = value;
264 Py_DECREF(tmp);
265 return 0;
268 static PyObject *
269 func_get_name(PyFunctionObject *op)
271 Py_INCREF(op->func_name);
272 return op->func_name;
275 static int
276 func_set_name(PyFunctionObject *op, PyObject *value)
278 PyObject *tmp;
280 if (restricted())
281 return -1;
282 /* Not legal to del f.func_name or to set it to anything
283 * other than a string object. */
284 if (value == NULL || !PyString_Check(value)) {
285 PyErr_SetString(PyExc_TypeError,
286 "__name__ must be set to a string object");
287 return -1;
289 tmp = op->func_name;
290 Py_INCREF(value);
291 op->func_name = value;
292 Py_DECREF(tmp);
293 return 0;
296 static PyObject *
297 func_get_defaults(PyFunctionObject *op)
299 if (restricted())
300 return NULL;
301 if (op->func_defaults == NULL) {
302 Py_INCREF(Py_None);
303 return Py_None;
305 Py_INCREF(op->func_defaults);
306 return op->func_defaults;
309 static int
310 func_set_defaults(PyFunctionObject *op, PyObject *value)
312 PyObject *tmp;
314 if (restricted())
315 return -1;
316 /* Legal to del f.func_defaults.
317 * Can only set func_defaults to NULL or a tuple. */
318 if (value == Py_None)
319 value = NULL;
320 if (value != NULL && !PyTuple_Check(value)) {
321 PyErr_SetString(PyExc_TypeError,
322 "__defaults__ must be set to a tuple object");
323 return -1;
325 tmp = op->func_defaults;
326 Py_XINCREF(value);
327 op->func_defaults = value;
328 Py_XDECREF(tmp);
329 return 0;
332 static PyGetSetDef func_getsetlist[] = {
333 {"func_code", (getter)func_get_code, (setter)func_set_code},
334 {"__code__", (getter)func_get_code, (setter)func_set_code},
335 {"func_defaults", (getter)func_get_defaults,
336 (setter)func_set_defaults},
337 {"__defaults__", (getter)func_get_defaults,
338 (setter)func_set_defaults},
339 {"func_dict", (getter)func_get_dict, (setter)func_set_dict},
340 {"__dict__", (getter)func_get_dict, (setter)func_set_dict},
341 {"func_name", (getter)func_get_name, (setter)func_set_name},
342 {"__name__", (getter)func_get_name, (setter)func_set_name},
343 {NULL} /* Sentinel */
346 PyDoc_STRVAR(func_doc,
347 "function(code, globals[, name[, argdefs[, closure]]])\n\
349 Create a function object from a code object and a dictionary.\n\
350 The optional name string overrides the name from the code object.\n\
351 The optional argdefs tuple specifies the default argument values.\n\
352 The optional closure tuple supplies the bindings for free variables.");
354 /* func_new() maintains the following invariants for closures. The
355 closure must correspond to the free variables of the code object.
357 if len(code.co_freevars) == 0:
358 closure = NULL
359 else:
360 len(closure) == len(code.co_freevars)
361 for every elt in closure, type(elt) == cell
364 static PyObject *
365 func_new(PyTypeObject* type, PyObject* args, PyObject* kw)
367 PyCodeObject *code;
368 PyObject *globals;
369 PyObject *name = Py_None;
370 PyObject *defaults = Py_None;
371 PyObject *closure = Py_None;
372 PyFunctionObject *newfunc;
373 Py_ssize_t nfree, nclosure;
374 static char *kwlist[] = {"code", "globals", "name",
375 "argdefs", "closure", 0};
377 if (!PyArg_ParseTupleAndKeywords(args, kw, "O!O!|OOO:function",
378 kwlist,
379 &PyCode_Type, &code,
380 &PyDict_Type, &globals,
381 &name, &defaults, &closure))
382 return NULL;
383 if (name != Py_None && !PyString_Check(name)) {
384 PyErr_SetString(PyExc_TypeError,
385 "arg 3 (name) must be None or string");
386 return NULL;
388 if (defaults != Py_None && !PyTuple_Check(defaults)) {
389 PyErr_SetString(PyExc_TypeError,
390 "arg 4 (defaults) must be None or tuple");
391 return NULL;
393 nfree = PyTuple_GET_SIZE(code->co_freevars);
394 if (!PyTuple_Check(closure)) {
395 if (nfree && closure == Py_None) {
396 PyErr_SetString(PyExc_TypeError,
397 "arg 5 (closure) must be tuple");
398 return NULL;
400 else if (closure != Py_None) {
401 PyErr_SetString(PyExc_TypeError,
402 "arg 5 (closure) must be None or tuple");
403 return NULL;
407 /* check that the closure is well-formed */
408 nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
409 if (nfree != nclosure)
410 return PyErr_Format(PyExc_ValueError,
411 "%s requires closure of length %zd, not %zd",
412 PyString_AS_STRING(code->co_name),
413 nfree, nclosure);
414 if (nclosure) {
415 Py_ssize_t i;
416 for (i = 0; i < nclosure; i++) {
417 PyObject *o = PyTuple_GET_ITEM(closure, i);
418 if (!PyCell_Check(o)) {
419 return PyErr_Format(PyExc_TypeError,
420 "arg 5 (closure) expected cell, found %s",
421 o->ob_type->tp_name);
426 newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
427 globals);
428 if (newfunc == NULL)
429 return NULL;
431 if (name != Py_None) {
432 Py_INCREF(name);
433 Py_DECREF(newfunc->func_name);
434 newfunc->func_name = name;
436 if (defaults != Py_None) {
437 Py_INCREF(defaults);
438 newfunc->func_defaults = defaults;
440 if (closure != Py_None) {
441 Py_INCREF(closure);
442 newfunc->func_closure = closure;
445 return (PyObject *)newfunc;
448 static void
449 func_dealloc(PyFunctionObject *op)
451 _PyObject_GC_UNTRACK(op);
452 if (op->func_weakreflist != NULL)
453 PyObject_ClearWeakRefs((PyObject *) op);
454 Py_DECREF(op->func_code);
455 Py_DECREF(op->func_globals);
456 Py_XDECREF(op->func_module);
457 Py_DECREF(op->func_name);
458 Py_XDECREF(op->func_defaults);
459 Py_XDECREF(op->func_doc);
460 Py_XDECREF(op->func_dict);
461 Py_XDECREF(op->func_closure);
462 PyObject_GC_Del(op);
465 static PyObject*
466 func_repr(PyFunctionObject *op)
468 return PyString_FromFormat("<function %s at %p>",
469 PyString_AsString(op->func_name),
470 op);
473 static int
474 func_traverse(PyFunctionObject *f, visitproc visit, void *arg)
476 Py_VISIT(f->func_code);
477 Py_VISIT(f->func_globals);
478 Py_VISIT(f->func_module);
479 Py_VISIT(f->func_defaults);
480 Py_VISIT(f->func_doc);
481 Py_VISIT(f->func_name);
482 Py_VISIT(f->func_dict);
483 Py_VISIT(f->func_closure);
484 return 0;
487 static PyObject *
488 function_call(PyObject *func, PyObject *arg, PyObject *kw)
490 PyObject *result;
491 PyObject *argdefs;
492 PyObject *kwtuple = NULL;
493 PyObject **d, **k;
494 Py_ssize_t nk, nd;
496 argdefs = PyFunction_GET_DEFAULTS(func);
497 if (argdefs != NULL && PyTuple_Check(argdefs)) {
498 d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0);
499 nd = PyTuple_GET_SIZE(argdefs);
501 else {
502 d = NULL;
503 nd = 0;
506 if (kw != NULL && PyDict_Check(kw)) {
507 Py_ssize_t pos, i;
508 nk = PyDict_Size(kw);
509 kwtuple = PyTuple_New(2*nk);
510 if (kwtuple == NULL)
511 return NULL;
512 k = &PyTuple_GET_ITEM(kwtuple, 0);
513 pos = i = 0;
514 while (PyDict_Next(kw, &pos, &k[i], &k[i+1])) {
515 Py_INCREF(k[i]);
516 Py_INCREF(k[i+1]);
517 i += 2;
519 nk = i/2;
521 else {
522 k = NULL;
523 nk = 0;
526 result = PyEval_EvalCodeEx(
527 (PyCodeObject *)PyFunction_GET_CODE(func),
528 PyFunction_GET_GLOBALS(func), (PyObject *)NULL,
529 &PyTuple_GET_ITEM(arg, 0), PyTuple_GET_SIZE(arg),
530 k, nk, d, nd,
531 PyFunction_GET_CLOSURE(func));
533 Py_XDECREF(kwtuple);
535 return result;
538 /* Bind a function to an object */
539 static PyObject *
540 func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
542 if (obj == Py_None)
543 obj = NULL;
544 return PyMethod_New(func, obj, type);
547 PyTypeObject PyFunction_Type = {
548 PyVarObject_HEAD_INIT(&PyType_Type, 0)
549 "function",
550 sizeof(PyFunctionObject),
552 (destructor)func_dealloc, /* tp_dealloc */
553 0, /* tp_print */
554 0, /* tp_getattr */
555 0, /* tp_setattr */
556 0, /* tp_compare */
557 (reprfunc)func_repr, /* tp_repr */
558 0, /* tp_as_number */
559 0, /* tp_as_sequence */
560 0, /* tp_as_mapping */
561 0, /* tp_hash */
562 function_call, /* tp_call */
563 0, /* tp_str */
564 PyObject_GenericGetAttr, /* tp_getattro */
565 PyObject_GenericSetAttr, /* tp_setattro */
566 0, /* tp_as_buffer */
567 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
568 func_doc, /* tp_doc */
569 (traverseproc)func_traverse, /* tp_traverse */
570 0, /* tp_clear */
571 0, /* tp_richcompare */
572 offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
573 0, /* tp_iter */
574 0, /* tp_iternext */
575 0, /* tp_methods */
576 func_memberlist, /* tp_members */
577 func_getsetlist, /* tp_getset */
578 0, /* tp_base */
579 0, /* tp_dict */
580 func_descr_get, /* tp_descr_get */
581 0, /* tp_descr_set */
582 offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */
583 0, /* tp_init */
584 0, /* tp_alloc */
585 func_new, /* tp_new */
589 /* Class method object */
591 /* A class method receives the class as implicit first argument,
592 just like an instance method receives the instance.
593 To declare a class method, use this idiom:
595 class C:
596 def f(cls, arg1, arg2, ...): ...
597 f = classmethod(f)
599 It can be called either on the class (e.g. C.f()) or on an instance
600 (e.g. C().f()); the instance is ignored except for its class.
601 If a class method is called for a derived class, the derived class
602 object is passed as the implied first argument.
604 Class methods are different than C++ or Java static methods.
605 If you want those, see static methods below.
608 typedef struct {
609 PyObject_HEAD
610 PyObject *cm_callable;
611 } classmethod;
613 static void
614 cm_dealloc(classmethod *cm)
616 _PyObject_GC_UNTRACK((PyObject *)cm);
617 Py_XDECREF(cm->cm_callable);
618 Py_TYPE(cm)->tp_free((PyObject *)cm);
621 static int
622 cm_traverse(classmethod *cm, visitproc visit, void *arg)
624 Py_VISIT(cm->cm_callable);
625 return 0;
628 static int
629 cm_clear(classmethod *cm)
631 Py_CLEAR(cm->cm_callable);
632 return 0;
636 static PyObject *
637 cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
639 classmethod *cm = (classmethod *)self;
641 if (cm->cm_callable == NULL) {
642 PyErr_SetString(PyExc_RuntimeError,
643 "uninitialized classmethod object");
644 return NULL;
646 if (type == NULL)
647 type = (PyObject *)(Py_TYPE(obj));
648 return PyMethod_New(cm->cm_callable,
649 type, (PyObject *)(Py_TYPE(type)));
652 static int
653 cm_init(PyObject *self, PyObject *args, PyObject *kwds)
655 classmethod *cm = (classmethod *)self;
656 PyObject *callable;
658 if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable))
659 return -1;
660 if (!_PyArg_NoKeywords("classmethod", kwds))
661 return -1;
662 if (!PyCallable_Check(callable)) {
663 PyErr_Format(PyExc_TypeError, "'%s' object is not callable",
664 callable->ob_type->tp_name);
665 return -1;
668 Py_INCREF(callable);
669 cm->cm_callable = callable;
670 return 0;
673 static PyMemberDef cm_memberlist[] = {
674 {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY},
675 {NULL} /* Sentinel */
678 PyDoc_STRVAR(classmethod_doc,
679 "classmethod(function) -> method\n\
681 Convert a function to be a class method.\n\
683 A class method receives the class as implicit first argument,\n\
684 just like an instance method receives the instance.\n\
685 To declare a class method, use this idiom:\n\
687 class C:\n\
688 def f(cls, arg1, arg2, ...): ...\n\
689 f = classmethod(f)\n\
691 It can be called either on the class (e.g. C.f()) or on an instance\n\
692 (e.g. C().f()). The instance is ignored except for its class.\n\
693 If a class method is called for a derived class, the derived class\n\
694 object is passed as the implied first argument.\n\
696 Class methods are different than C++ or Java static methods.\n\
697 If you want those, see the staticmethod builtin.");
699 PyTypeObject PyClassMethod_Type = {
700 PyVarObject_HEAD_INIT(&PyType_Type, 0)
701 "classmethod",
702 sizeof(classmethod),
704 (destructor)cm_dealloc, /* tp_dealloc */
705 0, /* tp_print */
706 0, /* tp_getattr */
707 0, /* tp_setattr */
708 0, /* tp_compare */
709 0, /* tp_repr */
710 0, /* tp_as_number */
711 0, /* tp_as_sequence */
712 0, /* tp_as_mapping */
713 0, /* tp_hash */
714 0, /* tp_call */
715 0, /* tp_str */
716 PyObject_GenericGetAttr, /* tp_getattro */
717 0, /* tp_setattro */
718 0, /* tp_as_buffer */
719 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
720 classmethod_doc, /* tp_doc */
721 (traverseproc)cm_traverse, /* tp_traverse */
722 (inquiry)cm_clear, /* tp_clear */
723 0, /* tp_richcompare */
724 0, /* tp_weaklistoffset */
725 0, /* tp_iter */
726 0, /* tp_iternext */
727 0, /* tp_methods */
728 cm_memberlist, /* tp_members */
729 0, /* tp_getset */
730 0, /* tp_base */
731 0, /* tp_dict */
732 cm_descr_get, /* tp_descr_get */
733 0, /* tp_descr_set */
734 0, /* tp_dictoffset */
735 cm_init, /* tp_init */
736 PyType_GenericAlloc, /* tp_alloc */
737 PyType_GenericNew, /* tp_new */
738 PyObject_GC_Del, /* tp_free */
741 PyObject *
742 PyClassMethod_New(PyObject *callable)
744 classmethod *cm = (classmethod *)
745 PyType_GenericAlloc(&PyClassMethod_Type, 0);
746 if (cm != NULL) {
747 Py_INCREF(callable);
748 cm->cm_callable = callable;
750 return (PyObject *)cm;
754 /* Static method object */
756 /* A static method does not receive an implicit first argument.
757 To declare a static method, use this idiom:
759 class C:
760 def f(arg1, arg2, ...): ...
761 f = staticmethod(f)
763 It can be called either on the class (e.g. C.f()) or on an instance
764 (e.g. C().f()); the instance is ignored except for its class.
766 Static methods in Python are similar to those found in Java or C++.
767 For a more advanced concept, see class methods above.
770 typedef struct {
771 PyObject_HEAD
772 PyObject *sm_callable;
773 } staticmethod;
775 static void
776 sm_dealloc(staticmethod *sm)
778 _PyObject_GC_UNTRACK((PyObject *)sm);
779 Py_XDECREF(sm->sm_callable);
780 Py_TYPE(sm)->tp_free((PyObject *)sm);
783 static int
784 sm_traverse(staticmethod *sm, visitproc visit, void *arg)
786 Py_VISIT(sm->sm_callable);
787 return 0;
790 static int
791 sm_clear(staticmethod *sm)
793 Py_XDECREF(sm->sm_callable);
794 sm->sm_callable = NULL;
796 return 0;
799 static PyObject *
800 sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
802 staticmethod *sm = (staticmethod *)self;
804 if (sm->sm_callable == NULL) {
805 PyErr_SetString(PyExc_RuntimeError,
806 "uninitialized staticmethod object");
807 return NULL;
809 Py_INCREF(sm->sm_callable);
810 return sm->sm_callable;
813 static int
814 sm_init(PyObject *self, PyObject *args, PyObject *kwds)
816 staticmethod *sm = (staticmethod *)self;
817 PyObject *callable;
819 if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable))
820 return -1;
821 if (!_PyArg_NoKeywords("staticmethod", kwds))
822 return -1;
823 Py_INCREF(callable);
824 sm->sm_callable = callable;
825 return 0;
828 static PyMemberDef sm_memberlist[] = {
829 {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY},
830 {NULL} /* Sentinel */
833 PyDoc_STRVAR(staticmethod_doc,
834 "staticmethod(function) -> method\n\
836 Convert a function to be a static method.\n\
838 A static method does not receive an implicit first argument.\n\
839 To declare a static method, use this idiom:\n\
841 class C:\n\
842 def f(arg1, arg2, ...): ...\n\
843 f = staticmethod(f)\n\
845 It can be called either on the class (e.g. C.f()) or on an instance\n\
846 (e.g. C().f()). The instance is ignored except for its class.\n\
848 Static methods in Python are similar to those found in Java or C++.\n\
849 For a more advanced concept, see the classmethod builtin.");
851 PyTypeObject PyStaticMethod_Type = {
852 PyVarObject_HEAD_INIT(&PyType_Type, 0)
853 "staticmethod",
854 sizeof(staticmethod),
856 (destructor)sm_dealloc, /* tp_dealloc */
857 0, /* tp_print */
858 0, /* tp_getattr */
859 0, /* tp_setattr */
860 0, /* tp_compare */
861 0, /* tp_repr */
862 0, /* tp_as_number */
863 0, /* tp_as_sequence */
864 0, /* tp_as_mapping */
865 0, /* tp_hash */
866 0, /* tp_call */
867 0, /* tp_str */
868 PyObject_GenericGetAttr, /* tp_getattro */
869 0, /* tp_setattro */
870 0, /* tp_as_buffer */
871 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
872 staticmethod_doc, /* tp_doc */
873 (traverseproc)sm_traverse, /* tp_traverse */
874 (inquiry)sm_clear, /* tp_clear */
875 0, /* tp_richcompare */
876 0, /* tp_weaklistoffset */
877 0, /* tp_iter */
878 0, /* tp_iternext */
879 0, /* tp_methods */
880 sm_memberlist, /* tp_members */
881 0, /* tp_getset */
882 0, /* tp_base */
883 0, /* tp_dict */
884 sm_descr_get, /* tp_descr_get */
885 0, /* tp_descr_set */
886 0, /* tp_dictoffset */
887 sm_init, /* tp_init */
888 PyType_GenericAlloc, /* tp_alloc */
889 PyType_GenericNew, /* tp_new */
890 PyObject_GC_Del, /* tp_free */
893 PyObject *
894 PyStaticMethod_New(PyObject *callable)
896 staticmethod *sm = (staticmethod *)
897 PyType_GenericAlloc(&PyStaticMethod_Type, 0);
898 if (sm != NULL) {
899 Py_INCREF(callable);
900 sm->sm_callable = callable;
902 return (PyObject *)sm;