2 /* Function object implementation */
7 #include "structmember.h"
10 PyFunction_New(PyObject
*code
, PyObject
*globals
)
12 PyFunctionObject
*op
= PyObject_GC_New(PyFunctionObject
,
14 static PyObject
*__name__
= 0;
19 op
->func_weakreflist
= NULL
;
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
))
39 op
->func_module
= NULL
;
41 /* __module__: If module name is in globals, use it.
45 __name__
= PyString_InternFromString("__name__");
51 module
= PyDict_GetItem(globals
, __name__
);
54 op
->func_module
= module
;
59 _PyObject_GC_TRACK(op
);
60 return (PyObject
*)op
;
64 PyFunction_GetCode(PyObject
*op
)
66 if (!PyFunction_Check(op
)) {
67 PyErr_BadInternalCall();
70 return ((PyFunctionObject
*) op
) -> func_code
;
74 PyFunction_GetGlobals(PyObject
*op
)
76 if (!PyFunction_Check(op
)) {
77 PyErr_BadInternalCall();
80 return ((PyFunctionObject
*) op
) -> func_globals
;
84 PyFunction_GetModule(PyObject
*op
)
86 if (!PyFunction_Check(op
)) {
87 PyErr_BadInternalCall();
90 return ((PyFunctionObject
*) op
) -> func_module
;
94 PyFunction_GetDefaults(PyObject
*op
)
96 if (!PyFunction_Check(op
)) {
97 PyErr_BadInternalCall();
100 return ((PyFunctionObject
*) op
) -> func_defaults
;
104 PyFunction_SetDefaults(PyObject
*op
, PyObject
*defaults
)
106 if (!PyFunction_Check(op
)) {
107 PyErr_BadInternalCall();
110 if (defaults
== Py_None
)
112 else if (PyTuple_Check(defaults
)) {
113 Py_XINCREF(defaults
);
116 PyErr_SetString(PyExc_SystemError
, "non-tuple default args");
119 Py_XDECREF(((PyFunctionObject
*) op
) -> func_defaults
);
120 ((PyFunctionObject
*) op
) -> func_defaults
= defaults
;
125 PyFunction_GetClosure(PyObject
*op
)
127 if (!PyFunction_Check(op
)) {
128 PyErr_BadInternalCall();
131 return ((PyFunctionObject
*) op
) -> func_closure
;
135 PyFunction_SetClosure(PyObject
*op
, PyObject
*closure
)
137 if (!PyFunction_Check(op
)) {
138 PyErr_BadInternalCall();
141 if (closure
== Py_None
)
143 else if (PyTuple_Check(closure
)) {
147 PyErr_Format(PyExc_SystemError
,
148 "expected tuple for closure, got '%.100s'",
149 closure
->ob_type
->tp_name
);
152 Py_XDECREF(((PyFunctionObject
*) op
) -> func_closure
);
153 ((PyFunctionObject
*) op
) -> func_closure
= closure
;
159 #define OFF(x) offsetof(PyFunctionObject, x)
161 static PyMemberDef func_memberlist
[] = {
162 {"func_closure", T_OBJECT
, OFF(func_closure
),
163 RESTRICTED
|READONLY
},
164 {"func_doc", T_OBJECT
, OFF(func_doc
), WRITE_RESTRICTED
},
165 {"__doc__", T_OBJECT
, OFF(func_doc
), WRITE_RESTRICTED
},
166 {"func_globals", T_OBJECT
, OFF(func_globals
),
167 RESTRICTED
|READONLY
},
168 {"__module__", T_OBJECT
, OFF(func_module
), WRITE_RESTRICTED
},
169 {NULL
} /* Sentinel */
175 if (!PyEval_GetRestricted())
177 PyErr_SetString(PyExc_RuntimeError
,
178 "function attributes not accessible in restricted mode");
183 func_get_dict(PyFunctionObject
*op
)
187 if (op
->func_dict
== NULL
) {
188 op
->func_dict
= PyDict_New();
189 if (op
->func_dict
== NULL
)
192 Py_INCREF(op
->func_dict
);
193 return op
->func_dict
;
197 func_set_dict(PyFunctionObject
*op
, PyObject
*value
)
203 /* It is illegal to del f.func_dict */
205 PyErr_SetString(PyExc_TypeError
,
206 "function's dictionary may not be deleted");
209 /* Can only set func_dict to a dictionary */
210 if (!PyDict_Check(value
)) {
211 PyErr_SetString(PyExc_TypeError
,
212 "setting function's dictionary to a non-dict");
217 op
->func_dict
= value
;
223 func_get_code(PyFunctionObject
*op
)
227 Py_INCREF(op
->func_code
);
228 return op
->func_code
;
232 func_set_code(PyFunctionObject
*op
, PyObject
*value
)
235 Py_ssize_t nfree
, nclosure
;
239 /* Not legal to del f.func_code or to set it to anything
240 * other than a code object. */
241 if (value
== NULL
|| !PyCode_Check(value
)) {
242 PyErr_SetString(PyExc_TypeError
,
243 "func_code must be set to a code object");
246 nfree
= PyCode_GetNumFree((PyCodeObject
*)value
);
247 nclosure
= (op
->func_closure
== NULL
? 0 :
248 PyTuple_GET_SIZE(op
->func_closure
));
249 if (nclosure
!= nfree
) {
250 PyErr_Format(PyExc_ValueError
,
251 "%s() requires a code object with %zd free vars,"
253 PyString_AsString(op
->func_name
),
259 op
->func_code
= value
;
265 func_get_name(PyFunctionObject
*op
)
267 Py_INCREF(op
->func_name
);
268 return op
->func_name
;
272 func_set_name(PyFunctionObject
*op
, PyObject
*value
)
278 /* Not legal to del f.func_name or to set it to anything
279 * other than a string object. */
280 if (value
== NULL
|| !PyString_Check(value
)) {
281 PyErr_SetString(PyExc_TypeError
,
282 "func_name must be set to a string object");
287 op
->func_name
= value
;
293 func_get_defaults(PyFunctionObject
*op
)
297 if (op
->func_defaults
== NULL
) {
301 Py_INCREF(op
->func_defaults
);
302 return op
->func_defaults
;
306 func_set_defaults(PyFunctionObject
*op
, PyObject
*value
)
312 /* Legal to del f.func_defaults.
313 * Can only set func_defaults to NULL or a tuple. */
314 if (value
== Py_None
)
316 if (value
!= NULL
&& !PyTuple_Check(value
)) {
317 PyErr_SetString(PyExc_TypeError
,
318 "func_defaults must be set to a tuple object");
321 tmp
= op
->func_defaults
;
323 op
->func_defaults
= value
;
328 static PyGetSetDef func_getsetlist
[] = {
329 {"func_code", (getter
)func_get_code
, (setter
)func_set_code
},
330 {"func_defaults", (getter
)func_get_defaults
,
331 (setter
)func_set_defaults
},
332 {"func_dict", (getter
)func_get_dict
, (setter
)func_set_dict
},
333 {"__dict__", (getter
)func_get_dict
, (setter
)func_set_dict
},
334 {"func_name", (getter
)func_get_name
, (setter
)func_set_name
},
335 {"__name__", (getter
)func_get_name
, (setter
)func_set_name
},
336 {NULL
} /* Sentinel */
339 PyDoc_STRVAR(func_doc
,
340 "function(code, globals[, name[, argdefs[, closure]]])\n\
342 Create a function object from a code object and a dictionary.\n\
343 The optional name string overrides the name from the code object.\n\
344 The optional argdefs tuple specifies the default argument values.\n\
345 The optional closure tuple supplies the bindings for free variables.");
347 /* func_new() maintains the following invariants for closures. The
348 closure must correspond to the free variables of the code object.
350 if len(code.co_freevars) == 0:
353 len(closure) == len(code.co_freevars)
354 for every elt in closure, type(elt) == cell
358 func_new(PyTypeObject
* type
, PyObject
* args
, PyObject
* kw
)
362 PyObject
*name
= Py_None
;
363 PyObject
*defaults
= Py_None
;
364 PyObject
*closure
= Py_None
;
365 PyFunctionObject
*newfunc
;
366 Py_ssize_t nfree
, nclosure
;
367 static char *kwlist
[] = {"code", "globals", "name",
368 "argdefs", "closure", 0};
370 if (!PyArg_ParseTupleAndKeywords(args
, kw
, "O!O!|OOO:function",
373 &PyDict_Type
, &globals
,
374 &name
, &defaults
, &closure
))
376 if (name
!= Py_None
&& !PyString_Check(name
)) {
377 PyErr_SetString(PyExc_TypeError
,
378 "arg 3 (name) must be None or string");
381 if (defaults
!= Py_None
&& !PyTuple_Check(defaults
)) {
382 PyErr_SetString(PyExc_TypeError
,
383 "arg 4 (defaults) must be None or tuple");
386 nfree
= PyTuple_GET_SIZE(code
->co_freevars
);
387 if (!PyTuple_Check(closure
)) {
388 if (nfree
&& closure
== Py_None
) {
389 PyErr_SetString(PyExc_TypeError
,
390 "arg 5 (closure) must be tuple");
393 else if (closure
!= Py_None
) {
394 PyErr_SetString(PyExc_TypeError
,
395 "arg 5 (closure) must be None or tuple");
400 /* check that the closure is well-formed */
401 nclosure
= closure
== Py_None
? 0 : PyTuple_GET_SIZE(closure
);
402 if (nfree
!= nclosure
)
403 return PyErr_Format(PyExc_ValueError
,
404 "%s requires closure of length %zd, not %zd",
405 PyString_AS_STRING(code
->co_name
),
409 for (i
= 0; i
< nclosure
; i
++) {
410 PyObject
*o
= PyTuple_GET_ITEM(closure
, i
);
411 if (!PyCell_Check(o
)) {
412 return PyErr_Format(PyExc_TypeError
,
413 "arg 5 (closure) expected cell, found %s",
414 o
->ob_type
->tp_name
);
419 newfunc
= (PyFunctionObject
*)PyFunction_New((PyObject
*)code
,
424 if (name
!= Py_None
) {
426 Py_DECREF(newfunc
->func_name
);
427 newfunc
->func_name
= name
;
429 if (defaults
!= Py_None
) {
431 newfunc
->func_defaults
= defaults
;
433 if (closure
!= Py_None
) {
435 newfunc
->func_closure
= closure
;
438 return (PyObject
*)newfunc
;
442 func_dealloc(PyFunctionObject
*op
)
444 _PyObject_GC_UNTRACK(op
);
445 if (op
->func_weakreflist
!= NULL
)
446 PyObject_ClearWeakRefs((PyObject
*) op
);
447 Py_DECREF(op
->func_code
);
448 Py_DECREF(op
->func_globals
);
449 Py_XDECREF(op
->func_module
);
450 Py_DECREF(op
->func_name
);
451 Py_XDECREF(op
->func_defaults
);
452 Py_XDECREF(op
->func_doc
);
453 Py_XDECREF(op
->func_dict
);
454 Py_XDECREF(op
->func_closure
);
459 func_repr(PyFunctionObject
*op
)
461 return PyString_FromFormat("<function %s at %p>",
462 PyString_AsString(op
->func_name
),
467 func_traverse(PyFunctionObject
*f
, visitproc visit
, void *arg
)
471 err
= visit(f
->func_code
, arg
);
475 if (f
->func_globals
) {
476 err
= visit(f
->func_globals
, arg
);
480 if (f
->func_module
) {
481 err
= visit(f
->func_module
, arg
);
485 if (f
->func_defaults
) {
486 err
= visit(f
->func_defaults
, arg
);
491 err
= visit(f
->func_doc
, arg
);
496 err
= visit(f
->func_name
, arg
);
501 err
= visit(f
->func_dict
, arg
);
505 if (f
->func_closure
) {
506 err
= visit(f
->func_closure
, arg
);
514 function_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
521 argdefs
= PyFunction_GET_DEFAULTS(func
);
522 if (argdefs
!= NULL
&& PyTuple_Check(argdefs
)) {
523 d
= &PyTuple_GET_ITEM((PyTupleObject
*)argdefs
, 0);
524 nd
= PyTuple_Size(argdefs
);
531 if (kw
!= NULL
&& PyDict_Check(kw
)) {
533 nk
= PyDict_Size(kw
);
534 k
= PyMem_NEW(PyObject
*, 2*nk
);
540 while (PyDict_Next(kw
, &pos
, &k
[i
], &k
[i
+1]))
543 /* XXX This is broken if the caller deletes dict items! */
550 result
= PyEval_EvalCodeEx(
551 (PyCodeObject
*)PyFunction_GET_CODE(func
),
552 PyFunction_GET_GLOBALS(func
), (PyObject
*)NULL
,
553 &PyTuple_GET_ITEM(arg
, 0), PyTuple_Size(arg
),
555 PyFunction_GET_CLOSURE(func
));
563 /* Bind a function to an object */
565 func_descr_get(PyObject
*func
, PyObject
*obj
, PyObject
*type
)
569 return PyMethod_New(func
, obj
, type
);
572 PyTypeObject PyFunction_Type
= {
573 PyObject_HEAD_INIT(&PyType_Type
)
576 sizeof(PyFunctionObject
),
578 (destructor
)func_dealloc
, /* tp_dealloc */
583 (reprfunc
)func_repr
, /* tp_repr */
584 0, /* tp_as_number */
585 0, /* tp_as_sequence */
586 0, /* tp_as_mapping */
588 function_call
, /* tp_call */
590 PyObject_GenericGetAttr
, /* tp_getattro */
591 PyObject_GenericSetAttr
, /* tp_setattro */
592 0, /* tp_as_buffer */
593 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
594 func_doc
, /* tp_doc */
595 (traverseproc
)func_traverse
, /* tp_traverse */
597 0, /* tp_richcompare */
598 offsetof(PyFunctionObject
, func_weakreflist
), /* tp_weaklistoffset */
602 func_memberlist
, /* tp_members */
603 func_getsetlist
, /* tp_getset */
606 func_descr_get
, /* tp_descr_get */
607 0, /* tp_descr_set */
608 offsetof(PyFunctionObject
, func_dict
), /* tp_dictoffset */
611 func_new
, /* tp_new */
615 /* 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:
622 def f(cls, arg1, arg2, ...): ...
625 It can be called either on the class (e.g. C.f()) or on an instance
626 (e.g. C().f()); the instance is ignored except for its class.
627 If a class method is called for a derived class, the derived class
628 object is passed as the implied first argument.
630 Class methods are different than C++ or Java static methods.
631 If you want those, see static methods below.
636 PyObject
*cm_callable
;
640 cm_dealloc(classmethod
*cm
)
642 _PyObject_GC_UNTRACK((PyObject
*)cm
);
643 Py_XDECREF(cm
->cm_callable
);
644 cm
->ob_type
->tp_free((PyObject
*)cm
);
648 cm_traverse(classmethod
*cm
, visitproc visit
, void *arg
)
650 if (!cm
->cm_callable
)
652 return visit(cm
->cm_callable
, arg
);
656 cm_clear(classmethod
*cm
)
658 Py_XDECREF(cm
->cm_callable
);
659 cm
->cm_callable
= NULL
;
666 cm_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
668 classmethod
*cm
= (classmethod
*)self
;
670 if (cm
->cm_callable
== NULL
) {
671 PyErr_SetString(PyExc_RuntimeError
,
672 "uninitialized classmethod object");
676 type
= (PyObject
*)(obj
->ob_type
);
677 return PyMethod_New(cm
->cm_callable
,
678 type
, (PyObject
*)(type
->ob_type
));
682 cm_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
684 classmethod
*cm
= (classmethod
*)self
;
687 if (!PyArg_UnpackTuple(args
, "classmethod", 1, 1, &callable
))
689 if (!_PyArg_NoKeywords("classmethod", kwds
))
691 if (!PyCallable_Check(callable
)) {
692 PyErr_Format(PyExc_TypeError
, "'%s' object is not callable",
693 callable
->ob_type
->tp_name
);
698 cm
->cm_callable
= callable
;
702 PyDoc_STRVAR(classmethod_doc
,
703 "classmethod(function) -> method\n\
705 Convert a function to be a class method.\n\
707 A class method receives the class as implicit first argument,\n\
708 just like an instance method receives the instance.\n\
709 To declare a class method, use this idiom:\n\
712 def f(cls, arg1, arg2, ...): ...\n\
713 f = classmethod(f)\n\
715 It can be called either on the class (e.g. C.f()) or on an instance\n\
716 (e.g. C().f()). The instance is ignored except for its class.\n\
717 If a class method is called for a derived class, the derived class\n\
718 object is passed as the implied first argument.\n\
720 Class methods are different than C++ or Java static methods.\n\
721 If you want those, see the staticmethod builtin.");
723 PyTypeObject PyClassMethod_Type
= {
724 PyObject_HEAD_INIT(&PyType_Type
)
729 (destructor
)cm_dealloc
, /* tp_dealloc */
735 0, /* tp_as_number */
736 0, /* tp_as_sequence */
737 0, /* tp_as_mapping */
741 PyObject_GenericGetAttr
, /* tp_getattro */
743 0, /* tp_as_buffer */
744 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
745 classmethod_doc
, /* tp_doc */
746 (traverseproc
)cm_traverse
, /* tp_traverse */
747 (inquiry
)cm_clear
, /* tp_clear */
748 0, /* tp_richcompare */
749 0, /* tp_weaklistoffset */
757 cm_descr_get
, /* tp_descr_get */
758 0, /* tp_descr_set */
759 0, /* tp_dictoffset */
760 cm_init
, /* tp_init */
761 PyType_GenericAlloc
, /* tp_alloc */
762 PyType_GenericNew
, /* tp_new */
763 PyObject_GC_Del
, /* tp_free */
767 PyClassMethod_New(PyObject
*callable
)
769 classmethod
*cm
= (classmethod
*)
770 PyType_GenericAlloc(&PyClassMethod_Type
, 0);
773 cm
->cm_callable
= callable
;
775 return (PyObject
*)cm
;
779 /* Static method object */
781 /* A static method does not receive an implicit first argument.
782 To declare a static method, use this idiom:
785 def f(arg1, arg2, ...): ...
788 It can be called either on the class (e.g. C.f()) or on an instance
789 (e.g. C().f()); the instance is ignored except for its class.
791 Static methods in Python are similar to those found in Java or C++.
792 For a more advanced concept, see class methods above.
797 PyObject
*sm_callable
;
801 sm_dealloc(staticmethod
*sm
)
803 _PyObject_GC_UNTRACK((PyObject
*)sm
);
804 Py_XDECREF(sm
->sm_callable
);
805 sm
->ob_type
->tp_free((PyObject
*)sm
);
809 sm_traverse(staticmethod
*sm
, visitproc visit
, void *arg
)
811 if (!sm
->sm_callable
)
813 return visit(sm
->sm_callable
, arg
);
817 sm_clear(staticmethod
*sm
)
819 Py_XDECREF(sm
->sm_callable
);
820 sm
->sm_callable
= NULL
;
826 sm_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
828 staticmethod
*sm
= (staticmethod
*)self
;
830 if (sm
->sm_callable
== NULL
) {
831 PyErr_SetString(PyExc_RuntimeError
,
832 "uninitialized staticmethod object");
835 Py_INCREF(sm
->sm_callable
);
836 return sm
->sm_callable
;
840 sm_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
842 staticmethod
*sm
= (staticmethod
*)self
;
845 if (!PyArg_UnpackTuple(args
, "staticmethod", 1, 1, &callable
))
847 if (!_PyArg_NoKeywords("staticmethod", kwds
))
850 sm
->sm_callable
= callable
;
854 PyDoc_STRVAR(staticmethod_doc
,
855 "staticmethod(function) -> method\n\
857 Convert a function to be a static method.\n\
859 A static method does not receive an implicit first argument.\n\
860 To declare a static method, use this idiom:\n\
863 def f(arg1, arg2, ...): ...\n\
864 f = staticmethod(f)\n\
866 It can be called either on the class (e.g. C.f()) or on an instance\n\
867 (e.g. C().f()). The instance is ignored except for its class.\n\
869 Static methods in Python are similar to those found in Java or C++.\n\
870 For a more advanced concept, see the classmethod builtin.");
872 PyTypeObject PyStaticMethod_Type
= {
873 PyObject_HEAD_INIT(&PyType_Type
)
876 sizeof(staticmethod
),
878 (destructor
)sm_dealloc
, /* tp_dealloc */
884 0, /* tp_as_number */
885 0, /* tp_as_sequence */
886 0, /* tp_as_mapping */
890 PyObject_GenericGetAttr
, /* tp_getattro */
892 0, /* tp_as_buffer */
893 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
894 staticmethod_doc
, /* tp_doc */
895 (traverseproc
)sm_traverse
, /* tp_traverse */
896 (inquiry
)sm_clear
, /* tp_clear */
897 0, /* tp_richcompare */
898 0, /* tp_weaklistoffset */
906 sm_descr_get
, /* tp_descr_get */
907 0, /* tp_descr_set */
908 0, /* tp_dictoffset */
909 sm_init
, /* tp_init */
910 PyType_GenericAlloc
, /* tp_alloc */
911 PyType_GenericNew
, /* tp_new */
912 PyObject_GC_Del
, /* tp_free */
916 PyStaticMethod_New(PyObject
*callable
)
918 staticmethod
*sm
= (staticmethod
*)
919 PyType_GenericAlloc(&PyStaticMethod_Type
, 0);
922 sm
->sm_callable
= callable
;
924 return (PyObject
*)sm
;