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 (defaults
&& PyTuple_Check(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 {"__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 */
179 if (!PyEval_GetRestricted())
181 PyErr_SetString(PyExc_RuntimeError
,
182 "function attributes not accessible in restricted mode");
187 func_get_dict(PyFunctionObject
*op
)
191 if (op
->func_dict
== NULL
) {
192 op
->func_dict
= PyDict_New();
193 if (op
->func_dict
== NULL
)
196 Py_INCREF(op
->func_dict
);
197 return op
->func_dict
;
201 func_set_dict(PyFunctionObject
*op
, PyObject
*value
)
207 /* It is illegal to del f.func_dict */
209 PyErr_SetString(PyExc_TypeError
,
210 "function's dictionary may not be deleted");
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");
221 op
->func_dict
= value
;
227 func_get_code(PyFunctionObject
*op
)
231 Py_INCREF(op
->func_code
);
232 return op
->func_code
;
236 func_set_code(PyFunctionObject
*op
, PyObject
*value
)
239 Py_ssize_t nfree
, nclosure
;
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");
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,"
257 PyString_AsString(op
->func_name
),
263 op
->func_code
= value
;
269 func_get_name(PyFunctionObject
*op
)
271 Py_INCREF(op
->func_name
);
272 return op
->func_name
;
276 func_set_name(PyFunctionObject
*op
, PyObject
*value
)
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");
291 op
->func_name
= value
;
297 func_get_defaults(PyFunctionObject
*op
)
301 if (op
->func_defaults
== NULL
) {
305 Py_INCREF(op
->func_defaults
);
306 return op
->func_defaults
;
310 func_set_defaults(PyFunctionObject
*op
, PyObject
*value
)
316 /* Legal to del f.func_defaults.
317 * Can only set func_defaults to NULL or a tuple. */
318 if (value
== Py_None
)
320 if (value
!= NULL
&& !PyTuple_Check(value
)) {
321 PyErr_SetString(PyExc_TypeError
,
322 "__defaults__ must be set to a tuple object");
325 tmp
= op
->func_defaults
;
327 op
->func_defaults
= value
;
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:
360 len(closure) == len(code.co_freevars)
361 for every elt in closure, type(elt) == cell
365 func_new(PyTypeObject
* type
, PyObject
* args
, PyObject
* kw
)
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",
380 &PyDict_Type
, &globals
,
381 &name
, &defaults
, &closure
))
383 if (name
!= Py_None
&& !PyString_Check(name
)) {
384 PyErr_SetString(PyExc_TypeError
,
385 "arg 3 (name) must be None or string");
388 if (defaults
!= Py_None
&& !PyTuple_Check(defaults
)) {
389 PyErr_SetString(PyExc_TypeError
,
390 "arg 4 (defaults) must be None or tuple");
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");
400 else if (closure
!= Py_None
) {
401 PyErr_SetString(PyExc_TypeError
,
402 "arg 5 (closure) must be None or tuple");
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
),
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
,
431 if (name
!= Py_None
) {
433 Py_DECREF(newfunc
->func_name
);
434 newfunc
->func_name
= name
;
436 if (defaults
!= Py_None
) {
438 newfunc
->func_defaults
= defaults
;
440 if (closure
!= Py_None
) {
442 newfunc
->func_closure
= closure
;
445 return (PyObject
*)newfunc
;
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
);
466 func_repr(PyFunctionObject
*op
)
468 return PyString_FromFormat("<function %s at %p>",
469 PyString_AsString(op
->func_name
),
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
);
488 function_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
495 argdefs
= PyFunction_GET_DEFAULTS(func
);
496 if (argdefs
!= NULL
&& PyTuple_Check(argdefs
)) {
497 d
= &PyTuple_GET_ITEM((PyTupleObject
*)argdefs
, 0);
498 nd
= PyTuple_Size(argdefs
);
505 if (kw
!= NULL
&& PyDict_Check(kw
)) {
507 nk
= PyDict_Size(kw
);
508 k
= PyMem_NEW(PyObject
*, 2*nk
);
514 while (PyDict_Next(kw
, &pos
, &k
[i
], &k
[i
+1]))
517 /* XXX This is broken if the caller deletes dict items! */
524 result
= PyEval_EvalCodeEx(
525 (PyCodeObject
*)PyFunction_GET_CODE(func
),
526 PyFunction_GET_GLOBALS(func
), (PyObject
*)NULL
,
527 &PyTuple_GET_ITEM(arg
, 0), PyTuple_Size(arg
),
529 PyFunction_GET_CLOSURE(func
));
537 /* Bind a function to an object */
539 func_descr_get(PyObject
*func
, PyObject
*obj
, PyObject
*type
)
543 return PyMethod_New(func
, obj
, type
);
546 PyTypeObject PyFunction_Type
= {
547 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
549 sizeof(PyFunctionObject
),
551 (destructor
)func_dealloc
, /* tp_dealloc */
556 (reprfunc
)func_repr
, /* tp_repr */
557 0, /* tp_as_number */
558 0, /* tp_as_sequence */
559 0, /* tp_as_mapping */
561 function_call
, /* tp_call */
563 PyObject_GenericGetAttr
, /* tp_getattro */
564 PyObject_GenericSetAttr
, /* tp_setattro */
565 0, /* tp_as_buffer */
566 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
567 func_doc
, /* tp_doc */
568 (traverseproc
)func_traverse
, /* tp_traverse */
570 0, /* tp_richcompare */
571 offsetof(PyFunctionObject
, func_weakreflist
), /* tp_weaklistoffset */
575 func_memberlist
, /* tp_members */
576 func_getsetlist
, /* tp_getset */
579 func_descr_get
, /* tp_descr_get */
580 0, /* tp_descr_set */
581 offsetof(PyFunctionObject
, func_dict
), /* tp_dictoffset */
584 func_new
, /* tp_new */
588 /* Class method object */
590 /* A class method receives the class as implicit first argument,
591 just like an instance method receives the instance.
592 To declare a class method, use this idiom:
595 def f(cls, arg1, arg2, ...): ...
598 It can be called either on the class (e.g. C.f()) or on an instance
599 (e.g. C().f()); the instance is ignored except for its class.
600 If a class method is called for a derived class, the derived class
601 object is passed as the implied first argument.
603 Class methods are different than C++ or Java static methods.
604 If you want those, see static methods below.
609 PyObject
*cm_callable
;
613 cm_dealloc(classmethod
*cm
)
615 _PyObject_GC_UNTRACK((PyObject
*)cm
);
616 Py_XDECREF(cm
->cm_callable
);
617 Py_TYPE(cm
)->tp_free((PyObject
*)cm
);
621 cm_traverse(classmethod
*cm
, visitproc visit
, void *arg
)
623 Py_VISIT(cm
->cm_callable
);
628 cm_clear(classmethod
*cm
)
630 Py_CLEAR(cm
->cm_callable
);
636 cm_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
638 classmethod
*cm
= (classmethod
*)self
;
640 if (cm
->cm_callable
== NULL
) {
641 PyErr_SetString(PyExc_RuntimeError
,
642 "uninitialized classmethod object");
646 type
= (PyObject
*)(Py_TYPE(obj
));
647 return PyMethod_New(cm
->cm_callable
,
648 type
, (PyObject
*)(Py_TYPE(type
)));
652 cm_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
654 classmethod
*cm
= (classmethod
*)self
;
657 if (!PyArg_UnpackTuple(args
, "classmethod", 1, 1, &callable
))
659 if (!_PyArg_NoKeywords("classmethod", kwds
))
661 if (!PyCallable_Check(callable
)) {
662 PyErr_Format(PyExc_TypeError
, "'%s' object is not callable",
663 callable
->ob_type
->tp_name
);
668 cm
->cm_callable
= callable
;
672 PyDoc_STRVAR(classmethod_doc
,
673 "classmethod(function) -> method\n\
675 Convert a function to be a class method.\n\
677 A class method receives the class as implicit first argument,\n\
678 just like an instance method receives the instance.\n\
679 To declare a class method, use this idiom:\n\
682 def f(cls, arg1, arg2, ...): ...\n\
683 f = classmethod(f)\n\
685 It can be called either on the class (e.g. C.f()) or on an instance\n\
686 (e.g. C().f()). The instance is ignored except for its class.\n\
687 If a class method is called for a derived class, the derived class\n\
688 object is passed as the implied first argument.\n\
690 Class methods are different than C++ or Java static methods.\n\
691 If you want those, see the staticmethod builtin.");
693 PyTypeObject PyClassMethod_Type
= {
694 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
698 (destructor
)cm_dealloc
, /* tp_dealloc */
704 0, /* tp_as_number */
705 0, /* tp_as_sequence */
706 0, /* tp_as_mapping */
710 PyObject_GenericGetAttr
, /* tp_getattro */
712 0, /* tp_as_buffer */
713 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
714 classmethod_doc
, /* tp_doc */
715 (traverseproc
)cm_traverse
, /* tp_traverse */
716 (inquiry
)cm_clear
, /* tp_clear */
717 0, /* tp_richcompare */
718 0, /* tp_weaklistoffset */
726 cm_descr_get
, /* tp_descr_get */
727 0, /* tp_descr_set */
728 0, /* tp_dictoffset */
729 cm_init
, /* tp_init */
730 PyType_GenericAlloc
, /* tp_alloc */
731 PyType_GenericNew
, /* tp_new */
732 PyObject_GC_Del
, /* tp_free */
736 PyClassMethod_New(PyObject
*callable
)
738 classmethod
*cm
= (classmethod
*)
739 PyType_GenericAlloc(&PyClassMethod_Type
, 0);
742 cm
->cm_callable
= callable
;
744 return (PyObject
*)cm
;
748 /* Static method object */
750 /* A static method does not receive an implicit first argument.
751 To declare a static method, use this idiom:
754 def f(arg1, arg2, ...): ...
757 It can be called either on the class (e.g. C.f()) or on an instance
758 (e.g. C().f()); the instance is ignored except for its class.
760 Static methods in Python are similar to those found in Java or C++.
761 For a more advanced concept, see class methods above.
766 PyObject
*sm_callable
;
770 sm_dealloc(staticmethod
*sm
)
772 _PyObject_GC_UNTRACK((PyObject
*)sm
);
773 Py_XDECREF(sm
->sm_callable
);
774 Py_TYPE(sm
)->tp_free((PyObject
*)sm
);
778 sm_traverse(staticmethod
*sm
, visitproc visit
, void *arg
)
780 Py_VISIT(sm
->sm_callable
);
785 sm_clear(staticmethod
*sm
)
787 Py_XDECREF(sm
->sm_callable
);
788 sm
->sm_callable
= NULL
;
794 sm_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
796 staticmethod
*sm
= (staticmethod
*)self
;
798 if (sm
->sm_callable
== NULL
) {
799 PyErr_SetString(PyExc_RuntimeError
,
800 "uninitialized staticmethod object");
803 Py_INCREF(sm
->sm_callable
);
804 return sm
->sm_callable
;
808 sm_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
810 staticmethod
*sm
= (staticmethod
*)self
;
813 if (!PyArg_UnpackTuple(args
, "staticmethod", 1, 1, &callable
))
815 if (!_PyArg_NoKeywords("staticmethod", kwds
))
818 sm
->sm_callable
= callable
;
822 PyDoc_STRVAR(staticmethod_doc
,
823 "staticmethod(function) -> method\n\
825 Convert a function to be a static method.\n\
827 A static method does not receive an implicit first argument.\n\
828 To declare a static method, use this idiom:\n\
831 def f(arg1, arg2, ...): ...\n\
832 f = staticmethod(f)\n\
834 It can be called either on the class (e.g. C.f()) or on an instance\n\
835 (e.g. C().f()). The instance is ignored except for its class.\n\
837 Static methods in Python are similar to those found in Java or C++.\n\
838 For a more advanced concept, see the classmethod builtin.");
840 PyTypeObject PyStaticMethod_Type
= {
841 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
843 sizeof(staticmethod
),
845 (destructor
)sm_dealloc
, /* tp_dealloc */
851 0, /* tp_as_number */
852 0, /* tp_as_sequence */
853 0, /* tp_as_mapping */
857 PyObject_GenericGetAttr
, /* tp_getattro */
859 0, /* tp_as_buffer */
860 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
861 staticmethod_doc
, /* tp_doc */
862 (traverseproc
)sm_traverse
, /* tp_traverse */
863 (inquiry
)sm_clear
, /* tp_clear */
864 0, /* tp_richcompare */
865 0, /* tp_weaklistoffset */
873 sm_descr_get
, /* tp_descr_get */
874 0, /* tp_descr_set */
875 0, /* tp_dictoffset */
876 sm_init
, /* tp_init */
877 PyType_GenericAlloc
, /* tp_alloc */
878 PyType_GenericNew
, /* tp_new */
879 PyObject_GC_Del
, /* tp_free */
883 PyStaticMethod_New(PyObject
*callable
)
885 staticmethod
*sm
= (staticmethod
*)
886 PyType_GenericAlloc(&PyStaticMethod_Type
, 0);
889 sm
->sm_callable
= callable
;
891 return (PyObject
*)sm
;