2 /* Function object implementation */
7 #include "structmember.h"
10 PyFunction_New(PyObject
*code
, PyObject
*globals
)
12 PyFunctionObject
*op
= PyObject_GC_New(PyFunctionObject
,
17 op
->func_weakreflist
= NULL
;
21 op
->func_globals
= globals
;
22 op
->func_name
= ((PyCodeObject
*)code
)->co_name
;
23 Py_INCREF(op
->func_name
);
24 op
->func_defaults
= NULL
; /* No default arguments */
25 op
->func_closure
= NULL
;
26 consts
= ((PyCodeObject
*)code
)->co_consts
;
27 if (PyTuple_Size(consts
) >= 1) {
28 doc
= PyTuple_GetItem(consts
, 0);
29 if (!PyString_Check(doc
) && !PyUnicode_Check(doc
))
40 _PyObject_GC_TRACK(op
);
41 return (PyObject
*)op
;
45 PyFunction_GetCode(PyObject
*op
)
47 if (!PyFunction_Check(op
)) {
48 PyErr_BadInternalCall();
51 return ((PyFunctionObject
*) op
) -> func_code
;
55 PyFunction_GetGlobals(PyObject
*op
)
57 if (!PyFunction_Check(op
)) {
58 PyErr_BadInternalCall();
61 return ((PyFunctionObject
*) op
) -> func_globals
;
65 PyFunction_GetDefaults(PyObject
*op
)
67 if (!PyFunction_Check(op
)) {
68 PyErr_BadInternalCall();
71 return ((PyFunctionObject
*) op
) -> func_defaults
;
75 PyFunction_SetDefaults(PyObject
*op
, PyObject
*defaults
)
77 if (!PyFunction_Check(op
)) {
78 PyErr_BadInternalCall();
81 if (defaults
== Py_None
)
83 else if (PyTuple_Check(defaults
)) {
87 PyErr_SetString(PyExc_SystemError
, "non-tuple default args");
90 Py_XDECREF(((PyFunctionObject
*) op
) -> func_defaults
);
91 ((PyFunctionObject
*) op
) -> func_defaults
= defaults
;
96 PyFunction_GetClosure(PyObject
*op
)
98 if (!PyFunction_Check(op
)) {
99 PyErr_BadInternalCall();
102 return ((PyFunctionObject
*) op
) -> func_closure
;
106 PyFunction_SetClosure(PyObject
*op
, PyObject
*closure
)
108 if (!PyFunction_Check(op
)) {
109 PyErr_BadInternalCall();
112 if (closure
== Py_None
)
114 else if (PyTuple_Check(closure
)) {
118 PyErr_SetString(PyExc_SystemError
, "non-tuple closure");
121 Py_XDECREF(((PyFunctionObject
*) op
) -> func_closure
);
122 ((PyFunctionObject
*) op
) -> func_closure
= closure
;
128 #define OFF(x) offsetof(PyFunctionObject, x)
132 static PyMemberDef func_memberlist
[] = {
133 {"func_closure", T_OBJECT
, OFF(func_closure
),
134 RESTRICTED
|READONLY
},
135 {"func_doc", T_OBJECT
, OFF(func_doc
), WRITE_RESTRICTED
},
136 {"__doc__", T_OBJECT
, OFF(func_doc
), WRITE_RESTRICTED
},
137 {"func_globals", T_OBJECT
, OFF(func_globals
),
138 RESTRICTED
|READONLY
},
139 {"func_name", T_OBJECT
, OFF(func_name
), READONLY
},
140 {"__name__", T_OBJECT
, OFF(func_name
), READONLY
},
141 {NULL
} /* Sentinel */
147 if (!PyEval_GetRestricted())
149 PyErr_SetString(PyExc_RuntimeError
,
150 "function attributes not accessible in restricted mode");
155 func_get_dict(PyFunctionObject
*op
)
159 if (op
->func_dict
== NULL
) {
160 op
->func_dict
= PyDict_New();
161 if (op
->func_dict
== NULL
)
164 Py_INCREF(op
->func_dict
);
165 return op
->func_dict
;
169 func_set_dict(PyFunctionObject
*op
, PyObject
*value
)
175 /* It is illegal to del f.func_dict */
177 PyErr_SetString(PyExc_TypeError
,
178 "function's dictionary may not be deleted");
181 /* Can only set func_dict to a dictionary */
182 if (!PyDict_Check(value
)) {
183 PyErr_SetString(PyExc_TypeError
,
184 "setting function's dictionary to a non-dict");
189 op
->func_dict
= value
;
195 func_get_code(PyFunctionObject
*op
)
199 Py_INCREF(op
->func_code
);
200 return op
->func_code
;
204 func_set_code(PyFunctionObject
*op
, PyObject
*value
)
210 /* Not legal to del f.func_code or to set it to anything
211 * other than a code object. */
212 if (value
== NULL
|| !PyCode_Check(value
)) {
213 PyErr_SetString(PyExc_TypeError
,
214 "func_code must be set to a code object");
219 op
->func_code
= value
;
225 func_get_defaults(PyFunctionObject
*op
)
229 if (op
->func_defaults
== NULL
) {
233 Py_INCREF(op
->func_defaults
);
234 return op
->func_defaults
;
238 func_set_defaults(PyFunctionObject
*op
, PyObject
*value
)
244 /* Legal to del f.func_defaults.
245 * Can only set func_defaults to NULL or a tuple. */
246 if (value
== Py_None
)
248 if (value
!= NULL
&& !PyTuple_Check(value
)) {
249 PyErr_SetString(PyExc_TypeError
,
250 "func_defaults must be set to a tuple object");
253 tmp
= op
->func_defaults
;
255 op
->func_defaults
= value
;
260 static PyGetSetDef func_getsetlist
[] = {
261 {"func_code", (getter
)func_get_code
, (setter
)func_set_code
},
262 {"func_defaults", (getter
)func_get_defaults
,
263 (setter
)func_set_defaults
},
264 {"func_dict", (getter
)func_get_dict
, (setter
)func_set_dict
},
265 {"__dict__", (getter
)func_get_dict
, (setter
)func_set_dict
},
266 {NULL
} /* Sentinel */
269 PyDoc_STRVAR(func_doc
,
270 "function(code, globals[, name[, argdefs[, closure]]])\n\
272 Create a function object from a code object and a dictionary.\n\
273 The optional name string overrides the name from the code object.\n\
274 The optional argdefs tuple specifies the default argument values.\n\
275 The optional closure tuple supplies the bindings for free variables.");
277 /* func_new() maintains the following invariants for closures. The
278 closure must correspond to the free variables of the code object.
280 if len(code.co_freevars) == 0:
283 len(closure) == len(code.co_freevars)
284 for every elt in closure, type(elt) == cell
288 func_new(PyTypeObject
* type
, PyObject
* args
, PyObject
* kw
)
292 PyObject
*name
= Py_None
;
293 PyObject
*defaults
= Py_None
;
294 PyObject
*closure
= Py_None
;
295 PyFunctionObject
*newfunc
;
298 if (!PyArg_ParseTuple(args
, "O!O!|OOO:function",
300 &PyDict_Type
, &globals
,
301 &name
, &defaults
, &closure
))
303 if (name
!= Py_None
&& !PyString_Check(name
)) {
304 PyErr_SetString(PyExc_TypeError
,
305 "arg 3 (name) must be None or string");
308 if (defaults
!= Py_None
&& !PyTuple_Check(defaults
)) {
309 PyErr_SetString(PyExc_TypeError
,
310 "arg 4 (defaults) must be None or tuple");
313 nfree
= PyTuple_GET_SIZE(code
->co_freevars
);
314 if (!PyTuple_Check(closure
)) {
315 if (nfree
&& closure
== Py_None
) {
316 PyErr_SetString(PyExc_TypeError
,
317 "arg 5 (closure) must be tuple");
320 else if (closure
!= Py_None
) {
321 PyErr_SetString(PyExc_TypeError
,
322 "arg 5 (closure) must be None or tuple");
327 /* check that the closure is well-formed */
328 nclosure
= closure
== Py_None
? 0 : PyTuple_GET_SIZE(closure
);
329 if (nfree
!= nclosure
)
330 return PyErr_Format(PyExc_ValueError
,
331 "%s requires closure of length %d, not %d",
332 PyString_AS_STRING(code
->co_name
),
336 for (i
= 0; i
< nclosure
; i
++) {
337 PyObject
*o
= PyTuple_GET_ITEM(closure
, i
);
338 if (!PyCell_Check(o
)) {
339 return PyErr_Format(PyExc_TypeError
,
340 "arg 5 (closure) expected cell, found %s",
341 o
->ob_type
->tp_name
);
346 newfunc
= (PyFunctionObject
*)PyFunction_New((PyObject
*)code
,
351 if (name
!= Py_None
) {
353 Py_DECREF(newfunc
->func_name
);
354 newfunc
->func_name
= name
;
356 if (defaults
!= Py_None
) {
358 newfunc
->func_defaults
= defaults
;
360 if (closure
!= Py_None
) {
362 newfunc
->func_closure
= closure
;
365 return (PyObject
*)newfunc
;
369 func_dealloc(PyFunctionObject
*op
)
371 _PyObject_GC_UNTRACK(op
);
372 if (op
->func_weakreflist
!= NULL
)
373 PyObject_ClearWeakRefs((PyObject
*) op
);
374 Py_DECREF(op
->func_code
);
375 Py_DECREF(op
->func_globals
);
376 Py_DECREF(op
->func_name
);
377 Py_XDECREF(op
->func_defaults
);
378 Py_XDECREF(op
->func_doc
);
379 Py_XDECREF(op
->func_dict
);
380 Py_XDECREF(op
->func_closure
);
385 func_repr(PyFunctionObject
*op
)
387 if (op
->func_name
== Py_None
)
388 return PyString_FromFormat("<anonymous function at %p>", op
);
389 return PyString_FromFormat("<function %s at %p>",
390 PyString_AsString(op
->func_name
),
395 func_traverse(PyFunctionObject
*f
, visitproc visit
, void *arg
)
399 err
= visit(f
->func_code
, arg
);
403 if (f
->func_globals
) {
404 err
= visit(f
->func_globals
, arg
);
408 if (f
->func_defaults
) {
409 err
= visit(f
->func_defaults
, arg
);
414 err
= visit(f
->func_doc
, arg
);
419 err
= visit(f
->func_name
, arg
);
424 err
= visit(f
->func_dict
, arg
);
428 if (f
->func_closure
) {
429 err
= visit(f
->func_closure
, arg
);
437 function_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
444 argdefs
= PyFunction_GET_DEFAULTS(func
);
445 if (argdefs
!= NULL
&& PyTuple_Check(argdefs
)) {
446 d
= &PyTuple_GET_ITEM((PyTupleObject
*)argdefs
, 0);
447 nd
= PyTuple_Size(argdefs
);
454 if (kw
!= NULL
&& PyDict_Check(kw
)) {
456 nk
= PyDict_Size(kw
);
457 k
= PyMem_NEW(PyObject
*, 2*nk
);
463 while (PyDict_Next(kw
, &pos
, &k
[i
], &k
[i
+1]))
466 /* XXX This is broken if the caller deletes dict items! */
473 result
= PyEval_EvalCodeEx(
474 (PyCodeObject
*)PyFunction_GET_CODE(func
),
475 PyFunction_GET_GLOBALS(func
), (PyObject
*)NULL
,
476 &PyTuple_GET_ITEM(arg
, 0), PyTuple_Size(arg
),
478 PyFunction_GET_CLOSURE(func
));
486 /* Bind a function to an object */
488 func_descr_get(PyObject
*func
, PyObject
*obj
, PyObject
*type
)
492 return PyMethod_New(func
, obj
, type
);
495 PyTypeObject PyFunction_Type
= {
496 PyObject_HEAD_INIT(&PyType_Type
)
499 sizeof(PyFunctionObject
),
501 (destructor
)func_dealloc
, /* tp_dealloc */
506 (reprfunc
)func_repr
, /* tp_repr */
507 0, /* tp_as_number */
508 0, /* tp_as_sequence */
509 0, /* tp_as_mapping */
511 function_call
, /* tp_call */
513 PyObject_GenericGetAttr
, /* tp_getattro */
514 PyObject_GenericSetAttr
, /* tp_setattro */
515 0, /* tp_as_buffer */
516 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
517 func_doc
, /* tp_doc */
518 (traverseproc
)func_traverse
, /* tp_traverse */
520 0, /* tp_richcompare */
521 offsetof(PyFunctionObject
, func_weakreflist
), /* tp_weaklistoffset */
525 func_memberlist
, /* tp_members */
526 func_getsetlist
, /* tp_getset */
529 func_descr_get
, /* tp_descr_get */
530 0, /* tp_descr_set */
531 offsetof(PyFunctionObject
, func_dict
), /* tp_dictoffset */
534 func_new
, /* tp_new */
538 /* Class method object */
540 /* A class method receives the class as implicit first argument,
541 just like an instance method receives the instance.
542 To declare a class method, use this idiom:
545 def f(cls, arg1, arg2, ...): ...
548 It can be called either on the class (e.g. C.f()) or on an instance
549 (e.g. C().f()); the instance is ignored except for its class.
550 If a class method is called for a derived class, the derived class
551 object is passed as the implied first argument.
553 Class methods are different than C++ or Java static methods.
554 If you want those, see static methods below.
559 PyObject
*cm_callable
;
563 cm_dealloc(classmethod
*cm
)
565 Py_XDECREF(cm
->cm_callable
);
566 cm
->ob_type
->tp_free((PyObject
*)cm
);
570 cm_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
572 classmethod
*cm
= (classmethod
*)self
;
574 if (cm
->cm_callable
== NULL
) {
575 PyErr_SetString(PyExc_RuntimeError
,
576 "uninitialized classmethod object");
580 type
= (PyObject
*)(obj
->ob_type
);
581 return PyMethod_New(cm
->cm_callable
,
582 type
, (PyObject
*)(type
->ob_type
));
586 cm_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
588 classmethod
*cm
= (classmethod
*)self
;
591 if (!PyArg_ParseTuple(args
, "O:classmethod", &callable
))
594 cm
->cm_callable
= callable
;
598 PyDoc_STRVAR(classmethod_doc
,
599 "classmethod(function) -> method\n\
601 Convert a function to be a class method.\n\
603 A class method receives the class as implicit first argument,\n\
604 just like an instance method receives the instance.\n\
605 To declare a class method, use this idiom:\n\
608 def f(cls, arg1, arg2, ...): ...\n\
609 f = classmethod(f)\n\
611 It can be called either on the class (e.g. C.f()) or on an instance\n\
612 (e.g. C().f()). The instance is ignored except for its class.\n\
613 If a class method is called for a derived class, the derived class\n\
614 object is passed as the implied first argument.\n\
616 Class methods are different than C++ or Java static methods.\n\
617 If you want those, see the staticmethod builtin.");
619 PyTypeObject PyClassMethod_Type
= {
620 PyObject_HEAD_INIT(&PyType_Type
)
625 (destructor
)cm_dealloc
, /* tp_dealloc */
631 0, /* tp_as_number */
632 0, /* tp_as_sequence */
633 0, /* tp_as_mapping */
637 PyObject_GenericGetAttr
, /* tp_getattro */
639 0, /* tp_as_buffer */
640 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
641 classmethod_doc
, /* tp_doc */
644 0, /* tp_richcompare */
645 0, /* tp_weaklistoffset */
653 cm_descr_get
, /* tp_descr_get */
654 0, /* tp_descr_set */
655 0, /* tp_dictoffset */
656 cm_init
, /* tp_init */
657 PyType_GenericAlloc
, /* tp_alloc */
658 PyType_GenericNew
, /* tp_new */
659 PyObject_Del
, /* tp_free */
663 PyClassMethod_New(PyObject
*callable
)
665 classmethod
*cm
= (classmethod
*)
666 PyType_GenericAlloc(&PyClassMethod_Type
, 0);
669 cm
->cm_callable
= callable
;
671 return (PyObject
*)cm
;
675 /* Static method object */
677 /* A static method does not receive an implicit first argument.
678 To declare a static method, use this idiom:
681 def f(arg1, arg2, ...): ...
684 It can be called either on the class (e.g. C.f()) or on an instance
685 (e.g. C().f()); the instance is ignored except for its class.
687 Static methods in Python are similar to those found in Java or C++.
688 For a more advanced concept, see class methods above.
693 PyObject
*sm_callable
;
697 sm_dealloc(staticmethod
*sm
)
699 Py_XDECREF(sm
->sm_callable
);
700 sm
->ob_type
->tp_free((PyObject
*)sm
);
704 sm_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
706 staticmethod
*sm
= (staticmethod
*)self
;
708 if (sm
->sm_callable
== NULL
) {
709 PyErr_SetString(PyExc_RuntimeError
,
710 "uninitialized staticmethod object");
713 Py_INCREF(sm
->sm_callable
);
714 return sm
->sm_callable
;
718 sm_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
720 staticmethod
*sm
= (staticmethod
*)self
;
723 if (!PyArg_ParseTuple(args
, "O:staticmethod", &callable
))
726 sm
->sm_callable
= callable
;
730 PyDoc_STRVAR(staticmethod_doc
,
731 "staticmethod(function) -> method\n\
733 Convert a function to be a static method.\n\
735 A static method does not receive an implicit first argument.\n\
736 To declare a static method, use this idiom:\n\
739 def f(arg1, arg2, ...): ...\n\
740 f = staticmethod(f)\n\
742 It can be called either on the class (e.g. C.f()) or on an instance\n\
743 (e.g. C().f()). The instance is ignored except for its class.\n\
745 Static methods in Python are similar to those found in Java or C++.\n\
746 For a more advanced concept, see the classmethod builtin.");
748 PyTypeObject PyStaticMethod_Type
= {
749 PyObject_HEAD_INIT(&PyType_Type
)
752 sizeof(staticmethod
),
754 (destructor
)sm_dealloc
, /* tp_dealloc */
760 0, /* tp_as_number */
761 0, /* tp_as_sequence */
762 0, /* tp_as_mapping */
766 PyObject_GenericGetAttr
, /* tp_getattro */
768 0, /* tp_as_buffer */
769 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
770 staticmethod_doc
, /* tp_doc */
773 0, /* tp_richcompare */
774 0, /* tp_weaklistoffset */
782 sm_descr_get
, /* tp_descr_get */
783 0, /* tp_descr_set */
784 0, /* tp_dictoffset */
785 sm_init
, /* tp_init */
786 PyType_GenericAlloc
, /* tp_alloc */
787 PyType_GenericNew
, /* tp_new */
788 PyObject_Del
, /* tp_free */
792 PyStaticMethod_New(PyObject
*callable
)
794 staticmethod
*sm
= (staticmethod
*)
795 PyType_GenericAlloc(&PyStaticMethod_Type
, 0);
798 sm
->sm_callable
= callable
;
800 return (PyObject
*)sm
;