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_SetString(PyExc_SystemError
, "non-tuple closure");
150 Py_XDECREF(((PyFunctionObject
*) op
) -> func_closure
);
151 ((PyFunctionObject
*) op
) -> func_closure
= closure
;
157 #define OFF(x) offsetof(PyFunctionObject, x)
159 static PyMemberDef func_memberlist
[] = {
160 {"func_closure", T_OBJECT
, OFF(func_closure
),
161 RESTRICTED
|READONLY
},
162 {"func_doc", T_OBJECT
, OFF(func_doc
), WRITE_RESTRICTED
},
163 {"__doc__", T_OBJECT
, OFF(func_doc
), WRITE_RESTRICTED
},
164 {"func_globals", T_OBJECT
, OFF(func_globals
),
165 RESTRICTED
|READONLY
},
166 {"func_name", T_OBJECT
, OFF(func_name
), READONLY
},
167 {"__name__", T_OBJECT
, OFF(func_name
), 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
)
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 "func_code must be set to a code object");
247 op
->func_code
= value
;
253 func_get_defaults(PyFunctionObject
*op
)
257 if (op
->func_defaults
== NULL
) {
261 Py_INCREF(op
->func_defaults
);
262 return op
->func_defaults
;
266 func_set_defaults(PyFunctionObject
*op
, PyObject
*value
)
272 /* Legal to del f.func_defaults.
273 * Can only set func_defaults to NULL or a tuple. */
274 if (value
== Py_None
)
276 if (value
!= NULL
&& !PyTuple_Check(value
)) {
277 PyErr_SetString(PyExc_TypeError
,
278 "func_defaults must be set to a tuple object");
281 tmp
= op
->func_defaults
;
283 op
->func_defaults
= value
;
288 static PyGetSetDef func_getsetlist
[] = {
289 {"func_code", (getter
)func_get_code
, (setter
)func_set_code
},
290 {"func_defaults", (getter
)func_get_defaults
,
291 (setter
)func_set_defaults
},
292 {"func_dict", (getter
)func_get_dict
, (setter
)func_set_dict
},
293 {"__dict__", (getter
)func_get_dict
, (setter
)func_set_dict
},
294 {NULL
} /* Sentinel */
297 PyDoc_STRVAR(func_doc
,
298 "function(code, globals[, name[, argdefs[, closure]]])\n\
300 Create a function object from a code object and a dictionary.\n\
301 The optional name string overrides the name from the code object.\n\
302 The optional argdefs tuple specifies the default argument values.\n\
303 The optional closure tuple supplies the bindings for free variables.");
305 /* func_new() maintains the following invariants for closures. The
306 closure must correspond to the free variables of the code object.
308 if len(code.co_freevars) == 0:
311 len(closure) == len(code.co_freevars)
312 for every elt in closure, type(elt) == cell
316 func_new(PyTypeObject
* type
, PyObject
* args
, PyObject
* kw
)
320 PyObject
*name
= Py_None
;
321 PyObject
*defaults
= Py_None
;
322 PyObject
*closure
= Py_None
;
323 PyFunctionObject
*newfunc
;
325 static char *kwlist
[] = {"code", "globals", "name",
326 "argdefs", "closure", 0};
328 if (!PyArg_ParseTupleAndKeywords(args
, kw
, "O!O!|OOO:function",
331 &PyDict_Type
, &globals
,
332 &name
, &defaults
, &closure
))
334 if (name
!= Py_None
&& !PyString_Check(name
)) {
335 PyErr_SetString(PyExc_TypeError
,
336 "arg 3 (name) must be None or string");
339 if (defaults
!= Py_None
&& !PyTuple_Check(defaults
)) {
340 PyErr_SetString(PyExc_TypeError
,
341 "arg 4 (defaults) must be None or tuple");
344 nfree
= PyTuple_GET_SIZE(code
->co_freevars
);
345 if (!PyTuple_Check(closure
)) {
346 if (nfree
&& closure
== Py_None
) {
347 PyErr_SetString(PyExc_TypeError
,
348 "arg 5 (closure) must be tuple");
351 else if (closure
!= Py_None
) {
352 PyErr_SetString(PyExc_TypeError
,
353 "arg 5 (closure) must be None or tuple");
358 /* check that the closure is well-formed */
359 nclosure
= closure
== Py_None
? 0 : PyTuple_GET_SIZE(closure
);
360 if (nfree
!= nclosure
)
361 return PyErr_Format(PyExc_ValueError
,
362 "%s requires closure of length %d, not %d",
363 PyString_AS_STRING(code
->co_name
),
367 for (i
= 0; i
< nclosure
; i
++) {
368 PyObject
*o
= PyTuple_GET_ITEM(closure
, i
);
369 if (!PyCell_Check(o
)) {
370 return PyErr_Format(PyExc_TypeError
,
371 "arg 5 (closure) expected cell, found %s",
372 o
->ob_type
->tp_name
);
377 newfunc
= (PyFunctionObject
*)PyFunction_New((PyObject
*)code
,
382 if (name
!= Py_None
) {
384 Py_DECREF(newfunc
->func_name
);
385 newfunc
->func_name
= name
;
387 if (defaults
!= Py_None
) {
389 newfunc
->func_defaults
= defaults
;
391 if (closure
!= Py_None
) {
393 newfunc
->func_closure
= closure
;
396 return (PyObject
*)newfunc
;
400 func_dealloc(PyFunctionObject
*op
)
402 _PyObject_GC_UNTRACK(op
);
403 if (op
->func_weakreflist
!= NULL
)
404 PyObject_ClearWeakRefs((PyObject
*) op
);
405 Py_DECREF(op
->func_code
);
406 Py_DECREF(op
->func_globals
);
407 Py_XDECREF(op
->func_module
);
408 Py_DECREF(op
->func_name
);
409 Py_XDECREF(op
->func_defaults
);
410 Py_XDECREF(op
->func_doc
);
411 Py_XDECREF(op
->func_dict
);
412 Py_XDECREF(op
->func_closure
);
417 func_repr(PyFunctionObject
*op
)
419 if (op
->func_name
== Py_None
)
420 return PyString_FromFormat("<anonymous function at %p>", op
);
421 return PyString_FromFormat("<function %s at %p>",
422 PyString_AsString(op
->func_name
),
427 func_traverse(PyFunctionObject
*f
, visitproc visit
, void *arg
)
431 err
= visit(f
->func_code
, arg
);
435 if (f
->func_globals
) {
436 err
= visit(f
->func_globals
, arg
);
440 if (f
->func_module
) {
441 err
= visit(f
->func_module
, arg
);
445 if (f
->func_defaults
) {
446 err
= visit(f
->func_defaults
, arg
);
451 err
= visit(f
->func_doc
, arg
);
456 err
= visit(f
->func_name
, arg
);
461 err
= visit(f
->func_dict
, arg
);
465 if (f
->func_closure
) {
466 err
= visit(f
->func_closure
, arg
);
474 function_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
481 argdefs
= PyFunction_GET_DEFAULTS(func
);
482 if (argdefs
!= NULL
&& PyTuple_Check(argdefs
)) {
483 d
= &PyTuple_GET_ITEM((PyTupleObject
*)argdefs
, 0);
484 nd
= PyTuple_Size(argdefs
);
491 if (kw
!= NULL
&& PyDict_Check(kw
)) {
493 nk
= PyDict_Size(kw
);
494 k
= PyMem_NEW(PyObject
*, 2*nk
);
500 while (PyDict_Next(kw
, &pos
, &k
[i
], &k
[i
+1]))
503 /* XXX This is broken if the caller deletes dict items! */
510 result
= PyEval_EvalCodeEx(
511 (PyCodeObject
*)PyFunction_GET_CODE(func
),
512 PyFunction_GET_GLOBALS(func
), (PyObject
*)NULL
,
513 &PyTuple_GET_ITEM(arg
, 0), PyTuple_Size(arg
),
515 PyFunction_GET_CLOSURE(func
));
523 /* Bind a function to an object */
525 func_descr_get(PyObject
*func
, PyObject
*obj
, PyObject
*type
)
529 return PyMethod_New(func
, obj
, type
);
532 PyTypeObject PyFunction_Type
= {
533 PyObject_HEAD_INIT(&PyType_Type
)
536 sizeof(PyFunctionObject
),
538 (destructor
)func_dealloc
, /* tp_dealloc */
543 (reprfunc
)func_repr
, /* tp_repr */
544 0, /* tp_as_number */
545 0, /* tp_as_sequence */
546 0, /* tp_as_mapping */
548 function_call
, /* tp_call */
550 PyObject_GenericGetAttr
, /* tp_getattro */
551 PyObject_GenericSetAttr
, /* tp_setattro */
552 0, /* tp_as_buffer */
553 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
554 func_doc
, /* tp_doc */
555 (traverseproc
)func_traverse
, /* tp_traverse */
557 0, /* tp_richcompare */
558 offsetof(PyFunctionObject
, func_weakreflist
), /* tp_weaklistoffset */
562 func_memberlist
, /* tp_members */
563 func_getsetlist
, /* tp_getset */
566 func_descr_get
, /* tp_descr_get */
567 0, /* tp_descr_set */
568 offsetof(PyFunctionObject
, func_dict
), /* tp_dictoffset */
571 func_new
, /* tp_new */
575 /* Class method object */
577 /* A class method receives the class as implicit first argument,
578 just like an instance method receives the instance.
579 To declare a class method, use this idiom:
582 def f(cls, arg1, arg2, ...): ...
585 It can be called either on the class (e.g. C.f()) or on an instance
586 (e.g. C().f()); the instance is ignored except for its class.
587 If a class method is called for a derived class, the derived class
588 object is passed as the implied first argument.
590 Class methods are different than C++ or Java static methods.
591 If you want those, see static methods below.
596 PyObject
*cm_callable
;
600 cm_dealloc(classmethod
*cm
)
602 _PyObject_GC_UNTRACK((PyObject
*)cm
);
603 Py_XDECREF(cm
->cm_callable
);
604 cm
->ob_type
->tp_free((PyObject
*)cm
);
608 cm_traverse(classmethod
*cm
, visitproc visit
, void *arg
)
610 if (!cm
->cm_callable
)
612 return visit(cm
->cm_callable
, arg
);
616 cm_clear(classmethod
*cm
)
618 Py_XDECREF(cm
->cm_callable
);
619 cm
->cm_callable
= NULL
;
626 cm_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
628 classmethod
*cm
= (classmethod
*)self
;
630 if (cm
->cm_callable
== NULL
) {
631 PyErr_SetString(PyExc_RuntimeError
,
632 "uninitialized classmethod object");
636 type
= (PyObject
*)(obj
->ob_type
);
637 return PyMethod_New(cm
->cm_callable
,
638 type
, (PyObject
*)(type
->ob_type
));
642 cm_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
644 classmethod
*cm
= (classmethod
*)self
;
647 if (!PyArg_UnpackTuple(args
, "classmethod", 1, 1, &callable
))
649 if (!PyCallable_Check(callable
)) {
650 PyErr_Format(PyExc_TypeError
, "'%s' object is not callable",
651 callable
->ob_type
->tp_name
);
656 cm
->cm_callable
= callable
;
660 PyDoc_STRVAR(classmethod_doc
,
661 "classmethod(function) -> method\n\
663 Convert a function to be a class method.\n\
665 A class method receives the class as implicit first argument,\n\
666 just like an instance method receives the instance.\n\
667 To declare a class method, use this idiom:\n\
670 def f(cls, arg1, arg2, ...): ...\n\
671 f = classmethod(f)\n\
673 It can be called either on the class (e.g. C.f()) or on an instance\n\
674 (e.g. C().f()). The instance is ignored except for its class.\n\
675 If a class method is called for a derived class, the derived class\n\
676 object is passed as the implied first argument.\n\
678 Class methods are different than C++ or Java static methods.\n\
679 If you want those, see the staticmethod builtin.");
681 PyTypeObject PyClassMethod_Type
= {
682 PyObject_HEAD_INIT(&PyType_Type
)
687 (destructor
)cm_dealloc
, /* tp_dealloc */
693 0, /* tp_as_number */
694 0, /* tp_as_sequence */
695 0, /* tp_as_mapping */
699 PyObject_GenericGetAttr
, /* tp_getattro */
701 0, /* tp_as_buffer */
702 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
703 classmethod_doc
, /* tp_doc */
704 (traverseproc
)cm_traverse
, /* tp_traverse */
705 (inquiry
)cm_clear
, /* tp_clear */
706 0, /* tp_richcompare */
707 0, /* tp_weaklistoffset */
715 cm_descr_get
, /* tp_descr_get */
716 0, /* tp_descr_set */
717 0, /* tp_dictoffset */
718 cm_init
, /* tp_init */
719 PyType_GenericAlloc
, /* tp_alloc */
720 PyType_GenericNew
, /* tp_new */
721 PyObject_GC_Del
, /* tp_free */
725 PyClassMethod_New(PyObject
*callable
)
727 classmethod
*cm
= (classmethod
*)
728 PyType_GenericAlloc(&PyClassMethod_Type
, 0);
731 cm
->cm_callable
= callable
;
733 return (PyObject
*)cm
;
737 /* Static method object */
739 /* A static method does not receive an implicit first argument.
740 To declare a static method, use this idiom:
743 def f(arg1, arg2, ...): ...
746 It can be called either on the class (e.g. C.f()) or on an instance
747 (e.g. C().f()); the instance is ignored except for its class.
749 Static methods in Python are similar to those found in Java or C++.
750 For a more advanced concept, see class methods above.
755 PyObject
*sm_callable
;
759 sm_dealloc(staticmethod
*sm
)
761 _PyObject_GC_UNTRACK((PyObject
*)sm
);
762 Py_XDECREF(sm
->sm_callable
);
763 sm
->ob_type
->tp_free((PyObject
*)sm
);
767 sm_traverse(staticmethod
*sm
, visitproc visit
, void *arg
)
769 if (!sm
->sm_callable
)
771 return visit(sm
->sm_callable
, arg
);
775 sm_clear(staticmethod
*sm
)
777 Py_XDECREF(sm
->sm_callable
);
778 sm
->sm_callable
= NULL
;
784 sm_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
786 staticmethod
*sm
= (staticmethod
*)self
;
788 if (sm
->sm_callable
== NULL
) {
789 PyErr_SetString(PyExc_RuntimeError
,
790 "uninitialized staticmethod object");
793 Py_INCREF(sm
->sm_callable
);
794 return sm
->sm_callable
;
798 sm_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
800 staticmethod
*sm
= (staticmethod
*)self
;
803 if (!PyArg_UnpackTuple(args
, "staticmethod", 1, 1, &callable
))
806 sm
->sm_callable
= callable
;
810 PyDoc_STRVAR(staticmethod_doc
,
811 "staticmethod(function) -> method\n\
813 Convert a function to be a static method.\n\
815 A static method does not receive an implicit first argument.\n\
816 To declare a static method, use this idiom:\n\
819 def f(arg1, arg2, ...): ...\n\
820 f = staticmethod(f)\n\
822 It can be called either on the class (e.g. C.f()) or on an instance\n\
823 (e.g. C().f()). The instance is ignored except for its class.\n\
825 Static methods in Python are similar to those found in Java or C++.\n\
826 For a more advanced concept, see the classmethod builtin.");
828 PyTypeObject PyStaticMethod_Type
= {
829 PyObject_HEAD_INIT(&PyType_Type
)
832 sizeof(staticmethod
),
834 (destructor
)sm_dealloc
, /* tp_dealloc */
840 0, /* tp_as_number */
841 0, /* tp_as_sequence */
842 0, /* tp_as_mapping */
846 PyObject_GenericGetAttr
, /* tp_getattro */
848 0, /* tp_as_buffer */
849 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
850 staticmethod_doc
, /* tp_doc */
851 (traverseproc
)sm_traverse
, /* tp_traverse */
852 (inquiry
)sm_clear
, /* tp_clear */
853 0, /* tp_richcompare */
854 0, /* tp_weaklistoffset */
862 sm_descr_get
, /* tp_descr_get */
863 0, /* tp_descr_set */
864 0, /* tp_dictoffset */
865 sm_init
, /* tp_init */
866 PyType_GenericAlloc
, /* tp_alloc */
867 PyType_GenericNew
, /* tp_new */
868 PyObject_GC_Del
, /* tp_free */
872 PyStaticMethod_New(PyObject
*callable
)
874 staticmethod
*sm
= (staticmethod
*)
875 PyType_GenericAlloc(&PyStaticMethod_Type
, 0);
878 sm
->sm_callable
= callable
;
880 return (PyObject
*)sm
;