2 /* Function object implementation */
7 #include "structmember.h"
10 PyFunction_New(PyObject
*code
, PyObject
*globals
)
12 PyFunctionObject
*op
= PyObject_GC_New(PyFunctionObject
,
18 op
->func_weakreflist
= NULL
;
22 op
->func_globals
= globals
;
23 op
->func_name
= ((PyCodeObject
*)code
)->co_name
;
24 Py_INCREF(op
->func_name
);
25 op
->func_defaults
= NULL
; /* No default arguments */
26 op
->func_closure
= NULL
;
27 consts
= ((PyCodeObject
*)code
)->co_consts
;
28 if (PyTuple_Size(consts
) >= 1) {
29 doc
= PyTuple_GetItem(consts
, 0);
30 if (!PyString_Check(doc
) && !PyUnicode_Check(doc
))
38 op
->func_module
= NULL
;
40 /* __module__: If module name is in globals, use it.
43 module
= PyDict_GetItemString(globals
, "__name__");
46 op
->func_module
= module
;
51 _PyObject_GC_TRACK(op
);
52 return (PyObject
*)op
;
56 PyFunction_GetCode(PyObject
*op
)
58 if (!PyFunction_Check(op
)) {
59 PyErr_BadInternalCall();
62 return ((PyFunctionObject
*) op
) -> func_code
;
66 PyFunction_GetGlobals(PyObject
*op
)
68 if (!PyFunction_Check(op
)) {
69 PyErr_BadInternalCall();
72 return ((PyFunctionObject
*) op
) -> func_globals
;
76 PyFunction_GetModule(PyObject
*op
)
78 if (!PyFunction_Check(op
)) {
79 PyErr_BadInternalCall();
82 return ((PyFunctionObject
*) op
) -> func_module
;
86 PyFunction_GetDefaults(PyObject
*op
)
88 if (!PyFunction_Check(op
)) {
89 PyErr_BadInternalCall();
92 return ((PyFunctionObject
*) op
) -> func_defaults
;
96 PyFunction_SetDefaults(PyObject
*op
, PyObject
*defaults
)
98 if (!PyFunction_Check(op
)) {
99 PyErr_BadInternalCall();
102 if (defaults
== Py_None
)
104 else if (PyTuple_Check(defaults
)) {
105 Py_XINCREF(defaults
);
108 PyErr_SetString(PyExc_SystemError
, "non-tuple default args");
111 Py_XDECREF(((PyFunctionObject
*) op
) -> func_defaults
);
112 ((PyFunctionObject
*) op
) -> func_defaults
= defaults
;
117 PyFunction_GetClosure(PyObject
*op
)
119 if (!PyFunction_Check(op
)) {
120 PyErr_BadInternalCall();
123 return ((PyFunctionObject
*) op
) -> func_closure
;
127 PyFunction_SetClosure(PyObject
*op
, PyObject
*closure
)
129 if (!PyFunction_Check(op
)) {
130 PyErr_BadInternalCall();
133 if (closure
== Py_None
)
135 else if (PyTuple_Check(closure
)) {
139 PyErr_SetString(PyExc_SystemError
, "non-tuple closure");
142 Py_XDECREF(((PyFunctionObject
*) op
) -> func_closure
);
143 ((PyFunctionObject
*) op
) -> func_closure
= closure
;
149 #define OFF(x) offsetof(PyFunctionObject, x)
153 static PyMemberDef func_memberlist
[] = {
154 {"func_closure", T_OBJECT
, OFF(func_closure
),
155 RESTRICTED
|READONLY
},
156 {"func_doc", T_OBJECT
, OFF(func_doc
), WRITE_RESTRICTED
},
157 {"__doc__", T_OBJECT
, OFF(func_doc
), WRITE_RESTRICTED
},
158 {"func_globals", T_OBJECT
, OFF(func_globals
),
159 RESTRICTED
|READONLY
},
160 {"func_name", T_OBJECT
, OFF(func_name
), READONLY
},
161 {"__name__", T_OBJECT
, OFF(func_name
), READONLY
},
162 {"__module__", T_OBJECT
, OFF(func_module
), WRITE_RESTRICTED
},
163 {NULL
} /* Sentinel */
169 if (!PyEval_GetRestricted())
171 PyErr_SetString(PyExc_RuntimeError
,
172 "function attributes not accessible in restricted mode");
177 func_get_dict(PyFunctionObject
*op
)
181 if (op
->func_dict
== NULL
) {
182 op
->func_dict
= PyDict_New();
183 if (op
->func_dict
== NULL
)
186 Py_INCREF(op
->func_dict
);
187 return op
->func_dict
;
191 func_set_dict(PyFunctionObject
*op
, PyObject
*value
)
197 /* It is illegal to del f.func_dict */
199 PyErr_SetString(PyExc_TypeError
,
200 "function's dictionary may not be deleted");
203 /* Can only set func_dict to a dictionary */
204 if (!PyDict_Check(value
)) {
205 PyErr_SetString(PyExc_TypeError
,
206 "setting function's dictionary to a non-dict");
211 op
->func_dict
= value
;
217 func_get_code(PyFunctionObject
*op
)
221 Py_INCREF(op
->func_code
);
222 return op
->func_code
;
226 func_set_code(PyFunctionObject
*op
, PyObject
*value
)
232 /* Not legal to del f.func_code or to set it to anything
233 * other than a code object. */
234 if (value
== NULL
|| !PyCode_Check(value
)) {
235 PyErr_SetString(PyExc_TypeError
,
236 "func_code must be set to a code object");
241 op
->func_code
= value
;
247 func_get_defaults(PyFunctionObject
*op
)
251 if (op
->func_defaults
== NULL
) {
255 Py_INCREF(op
->func_defaults
);
256 return op
->func_defaults
;
260 func_set_defaults(PyFunctionObject
*op
, PyObject
*value
)
266 /* Legal to del f.func_defaults.
267 * Can only set func_defaults to NULL or a tuple. */
268 if (value
== Py_None
)
270 if (value
!= NULL
&& !PyTuple_Check(value
)) {
271 PyErr_SetString(PyExc_TypeError
,
272 "func_defaults must be set to a tuple object");
275 tmp
= op
->func_defaults
;
277 op
->func_defaults
= value
;
282 static PyGetSetDef func_getsetlist
[] = {
283 {"func_code", (getter
)func_get_code
, (setter
)func_set_code
},
284 {"func_defaults", (getter
)func_get_defaults
,
285 (setter
)func_set_defaults
},
286 {"func_dict", (getter
)func_get_dict
, (setter
)func_set_dict
},
287 {"__dict__", (getter
)func_get_dict
, (setter
)func_set_dict
},
288 {NULL
} /* Sentinel */
291 PyDoc_STRVAR(func_doc
,
292 "function(code, globals[, name[, argdefs[, closure]]])\n\
294 Create a function object from a code object and a dictionary.\n\
295 The optional name string overrides the name from the code object.\n\
296 The optional argdefs tuple specifies the default argument values.\n\
297 The optional closure tuple supplies the bindings for free variables.");
299 /* func_new() maintains the following invariants for closures. The
300 closure must correspond to the free variables of the code object.
302 if len(code.co_freevars) == 0:
305 len(closure) == len(code.co_freevars)
306 for every elt in closure, type(elt) == cell
310 func_new(PyTypeObject
* type
, PyObject
* args
, PyObject
* kw
)
314 PyObject
*name
= Py_None
;
315 PyObject
*defaults
= Py_None
;
316 PyObject
*closure
= Py_None
;
317 PyFunctionObject
*newfunc
;
320 if (!PyArg_ParseTuple(args
, "O!O!|OOO:function",
322 &PyDict_Type
, &globals
,
323 &name
, &defaults
, &closure
))
325 if (name
!= Py_None
&& !PyString_Check(name
)) {
326 PyErr_SetString(PyExc_TypeError
,
327 "arg 3 (name) must be None or string");
330 if (defaults
!= Py_None
&& !PyTuple_Check(defaults
)) {
331 PyErr_SetString(PyExc_TypeError
,
332 "arg 4 (defaults) must be None or tuple");
335 nfree
= PyTuple_GET_SIZE(code
->co_freevars
);
336 if (!PyTuple_Check(closure
)) {
337 if (nfree
&& closure
== Py_None
) {
338 PyErr_SetString(PyExc_TypeError
,
339 "arg 5 (closure) must be tuple");
342 else if (closure
!= Py_None
) {
343 PyErr_SetString(PyExc_TypeError
,
344 "arg 5 (closure) must be None or tuple");
349 /* check that the closure is well-formed */
350 nclosure
= closure
== Py_None
? 0 : PyTuple_GET_SIZE(closure
);
351 if (nfree
!= nclosure
)
352 return PyErr_Format(PyExc_ValueError
,
353 "%s requires closure of length %d, not %d",
354 PyString_AS_STRING(code
->co_name
),
358 for (i
= 0; i
< nclosure
; i
++) {
359 PyObject
*o
= PyTuple_GET_ITEM(closure
, i
);
360 if (!PyCell_Check(o
)) {
361 return PyErr_Format(PyExc_TypeError
,
362 "arg 5 (closure) expected cell, found %s",
363 o
->ob_type
->tp_name
);
368 newfunc
= (PyFunctionObject
*)PyFunction_New((PyObject
*)code
,
373 if (name
!= Py_None
) {
375 Py_DECREF(newfunc
->func_name
);
376 newfunc
->func_name
= name
;
378 if (defaults
!= Py_None
) {
380 newfunc
->func_defaults
= defaults
;
382 if (closure
!= Py_None
) {
384 newfunc
->func_closure
= closure
;
387 return (PyObject
*)newfunc
;
391 func_dealloc(PyFunctionObject
*op
)
393 _PyObject_GC_UNTRACK(op
);
394 if (op
->func_weakreflist
!= NULL
)
395 PyObject_ClearWeakRefs((PyObject
*) op
);
396 Py_DECREF(op
->func_code
);
397 Py_DECREF(op
->func_globals
);
398 Py_XDECREF(op
->func_module
);
399 Py_DECREF(op
->func_name
);
400 Py_XDECREF(op
->func_defaults
);
401 Py_XDECREF(op
->func_doc
);
402 Py_XDECREF(op
->func_dict
);
403 Py_XDECREF(op
->func_closure
);
408 func_repr(PyFunctionObject
*op
)
410 if (op
->func_name
== Py_None
)
411 return PyString_FromFormat("<anonymous function at %p>", op
);
412 return PyString_FromFormat("<function %s at %p>",
413 PyString_AsString(op
->func_name
),
418 func_traverse(PyFunctionObject
*f
, visitproc visit
, void *arg
)
422 err
= visit(f
->func_code
, arg
);
426 if (f
->func_globals
) {
427 err
= visit(f
->func_globals
, arg
);
431 if (f
->func_module
) {
432 err
= visit(f
->func_module
, arg
);
436 if (f
->func_defaults
) {
437 err
= visit(f
->func_defaults
, arg
);
442 err
= visit(f
->func_doc
, arg
);
447 err
= visit(f
->func_name
, arg
);
452 err
= visit(f
->func_dict
, arg
);
456 if (f
->func_closure
) {
457 err
= visit(f
->func_closure
, arg
);
465 function_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
472 argdefs
= PyFunction_GET_DEFAULTS(func
);
473 if (argdefs
!= NULL
&& PyTuple_Check(argdefs
)) {
474 d
= &PyTuple_GET_ITEM((PyTupleObject
*)argdefs
, 0);
475 nd
= PyTuple_Size(argdefs
);
482 if (kw
!= NULL
&& PyDict_Check(kw
)) {
484 nk
= PyDict_Size(kw
);
485 k
= PyMem_NEW(PyObject
*, 2*nk
);
491 while (PyDict_Next(kw
, &pos
, &k
[i
], &k
[i
+1]))
494 /* XXX This is broken if the caller deletes dict items! */
501 result
= PyEval_EvalCodeEx(
502 (PyCodeObject
*)PyFunction_GET_CODE(func
),
503 PyFunction_GET_GLOBALS(func
), (PyObject
*)NULL
,
504 &PyTuple_GET_ITEM(arg
, 0), PyTuple_Size(arg
),
506 PyFunction_GET_CLOSURE(func
));
514 /* Bind a function to an object */
516 func_descr_get(PyObject
*func
, PyObject
*obj
, PyObject
*type
)
520 return PyMethod_New(func
, obj
, type
);
523 PyTypeObject PyFunction_Type
= {
524 PyObject_HEAD_INIT(&PyType_Type
)
527 sizeof(PyFunctionObject
),
529 (destructor
)func_dealloc
, /* tp_dealloc */
534 (reprfunc
)func_repr
, /* tp_repr */
535 0, /* tp_as_number */
536 0, /* tp_as_sequence */
537 0, /* tp_as_mapping */
539 function_call
, /* tp_call */
541 PyObject_GenericGetAttr
, /* tp_getattro */
542 PyObject_GenericSetAttr
, /* tp_setattro */
543 0, /* tp_as_buffer */
544 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
545 func_doc
, /* tp_doc */
546 (traverseproc
)func_traverse
, /* tp_traverse */
548 0, /* tp_richcompare */
549 offsetof(PyFunctionObject
, func_weakreflist
), /* tp_weaklistoffset */
553 func_memberlist
, /* tp_members */
554 func_getsetlist
, /* tp_getset */
557 func_descr_get
, /* tp_descr_get */
558 0, /* tp_descr_set */
559 offsetof(PyFunctionObject
, func_dict
), /* tp_dictoffset */
562 func_new
, /* tp_new */
566 /* Class method object */
568 /* A class method receives the class as implicit first argument,
569 just like an instance method receives the instance.
570 To declare a class method, use this idiom:
573 def f(cls, arg1, arg2, ...): ...
576 It can be called either on the class (e.g. C.f()) or on an instance
577 (e.g. C().f()); the instance is ignored except for its class.
578 If a class method is called for a derived class, the derived class
579 object is passed as the implied first argument.
581 Class methods are different than C++ or Java static methods.
582 If you want those, see static methods below.
587 PyObject
*cm_callable
;
591 cm_dealloc(classmethod
*cm
)
593 Py_XDECREF(cm
->cm_callable
);
594 cm
->ob_type
->tp_free((PyObject
*)cm
);
598 cm_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
600 classmethod
*cm
= (classmethod
*)self
;
602 if (cm
->cm_callable
== NULL
) {
603 PyErr_SetString(PyExc_RuntimeError
,
604 "uninitialized classmethod object");
608 type
= (PyObject
*)(obj
->ob_type
);
609 return PyMethod_New(cm
->cm_callable
,
610 type
, (PyObject
*)(type
->ob_type
));
614 cm_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
616 classmethod
*cm
= (classmethod
*)self
;
619 if (!PyArg_UnpackTuple(args
, "classmethod", 1, 1, &callable
))
622 cm
->cm_callable
= callable
;
626 PyDoc_STRVAR(classmethod_doc
,
627 "classmethod(function) -> method\n\
629 Convert a function to be a class method.\n\
631 A class method receives the class as implicit first argument,\n\
632 just like an instance method receives the instance.\n\
633 To declare a class method, use this idiom:\n\
636 def f(cls, arg1, arg2, ...): ...\n\
637 f = classmethod(f)\n\
639 It can be called either on the class (e.g. C.f()) or on an instance\n\
640 (e.g. C().f()). The instance is ignored except for its class.\n\
641 If a class method is called for a derived class, the derived class\n\
642 object is passed as the implied first argument.\n\
644 Class methods are different than C++ or Java static methods.\n\
645 If you want those, see the staticmethod builtin.");
647 PyTypeObject PyClassMethod_Type
= {
648 PyObject_HEAD_INIT(&PyType_Type
)
653 (destructor
)cm_dealloc
, /* tp_dealloc */
659 0, /* tp_as_number */
660 0, /* tp_as_sequence */
661 0, /* tp_as_mapping */
665 PyObject_GenericGetAttr
, /* tp_getattro */
667 0, /* tp_as_buffer */
668 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
669 classmethod_doc
, /* tp_doc */
672 0, /* tp_richcompare */
673 0, /* tp_weaklistoffset */
681 cm_descr_get
, /* tp_descr_get */
682 0, /* tp_descr_set */
683 0, /* tp_dictoffset */
684 cm_init
, /* tp_init */
685 PyType_GenericAlloc
, /* tp_alloc */
686 PyType_GenericNew
, /* tp_new */
687 PyObject_Del
, /* tp_free */
691 PyClassMethod_New(PyObject
*callable
)
693 classmethod
*cm
= (classmethod
*)
694 PyType_GenericAlloc(&PyClassMethod_Type
, 0);
697 cm
->cm_callable
= callable
;
699 return (PyObject
*)cm
;
703 /* Static method object */
705 /* A static method does not receive an implicit first argument.
706 To declare a static method, use this idiom:
709 def f(arg1, arg2, ...): ...
712 It can be called either on the class (e.g. C.f()) or on an instance
713 (e.g. C().f()); the instance is ignored except for its class.
715 Static methods in Python are similar to those found in Java or C++.
716 For a more advanced concept, see class methods above.
721 PyObject
*sm_callable
;
725 sm_dealloc(staticmethod
*sm
)
727 Py_XDECREF(sm
->sm_callable
);
728 sm
->ob_type
->tp_free((PyObject
*)sm
);
732 sm_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
734 staticmethod
*sm
= (staticmethod
*)self
;
736 if (sm
->sm_callable
== NULL
) {
737 PyErr_SetString(PyExc_RuntimeError
,
738 "uninitialized staticmethod object");
741 Py_INCREF(sm
->sm_callable
);
742 return sm
->sm_callable
;
746 sm_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
748 staticmethod
*sm
= (staticmethod
*)self
;
751 if (!PyArg_UnpackTuple(args
, "staticmethod", 1, 1, &callable
))
754 sm
->sm_callable
= callable
;
758 PyDoc_STRVAR(staticmethod_doc
,
759 "staticmethod(function) -> method\n\
761 Convert a function to be a static method.\n\
763 A static method does not receive an implicit first argument.\n\
764 To declare a static method, use this idiom:\n\
767 def f(arg1, arg2, ...): ...\n\
768 f = staticmethod(f)\n\
770 It can be called either on the class (e.g. C.f()) or on an instance\n\
771 (e.g. C().f()). The instance is ignored except for its class.\n\
773 Static methods in Python are similar to those found in Java or C++.\n\
774 For a more advanced concept, see the classmethod builtin.");
776 PyTypeObject PyStaticMethod_Type
= {
777 PyObject_HEAD_INIT(&PyType_Type
)
780 sizeof(staticmethod
),
782 (destructor
)sm_dealloc
, /* tp_dealloc */
788 0, /* tp_as_number */
789 0, /* tp_as_sequence */
790 0, /* tp_as_mapping */
794 PyObject_GenericGetAttr
, /* tp_getattro */
796 0, /* tp_as_buffer */
797 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
798 staticmethod_doc
, /* tp_doc */
801 0, /* tp_richcompare */
802 0, /* tp_weaklistoffset */
810 sm_descr_get
, /* tp_descr_get */
811 0, /* tp_descr_set */
812 0, /* tp_dictoffset */
813 sm_init
, /* tp_init */
814 PyType_GenericAlloc
, /* tp_alloc */
815 PyType_GenericNew
, /* tp_new */
816 PyObject_Del
, /* tp_free */
820 PyStaticMethod_New(PyObject
*callable
)
822 staticmethod
*sm
= (staticmethod
*)
823 PyType_GenericAlloc(&PyStaticMethod_Type
, 0);
826 sm
->sm_callable
= callable
;
828 return (PyObject
*)sm
;