This commit was manufactured by cvs2svn to create tag 'r221'.
[python/dscho.git] / Objects / funcobject.c
blob426b8f490a44e3ac50292b539762fac6e473e6a8
2 /* Function object implementation */
4 #include "Python.h"
5 #include "compile.h"
6 #include "eval.h"
7 #include "structmember.h"
9 PyObject *
10 PyFunction_New(PyObject *code, PyObject *globals)
12 PyFunctionObject *op = PyObject_GC_New(PyFunctionObject,
13 &PyFunction_Type);
14 if (op != NULL) {
15 PyObject *doc;
16 PyObject *consts;
17 op->func_weakreflist = NULL;
18 Py_INCREF(code);
19 op->func_code = code;
20 Py_INCREF(globals);
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))
30 doc = Py_None;
32 else
33 doc = Py_None;
34 Py_INCREF(doc);
35 op->func_doc = doc;
36 op->func_dict = NULL;
38 else
39 return NULL;
40 _PyObject_GC_TRACK(op);
41 return (PyObject *)op;
44 PyObject *
45 PyFunction_GetCode(PyObject *op)
47 if (!PyFunction_Check(op)) {
48 PyErr_BadInternalCall();
49 return NULL;
51 return ((PyFunctionObject *) op) -> func_code;
54 PyObject *
55 PyFunction_GetGlobals(PyObject *op)
57 if (!PyFunction_Check(op)) {
58 PyErr_BadInternalCall();
59 return NULL;
61 return ((PyFunctionObject *) op) -> func_globals;
64 PyObject *
65 PyFunction_GetDefaults(PyObject *op)
67 if (!PyFunction_Check(op)) {
68 PyErr_BadInternalCall();
69 return NULL;
71 return ((PyFunctionObject *) op) -> func_defaults;
74 int
75 PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
77 if (!PyFunction_Check(op)) {
78 PyErr_BadInternalCall();
79 return -1;
81 if (defaults == Py_None)
82 defaults = NULL;
83 else if (PyTuple_Check(defaults)) {
84 Py_XINCREF(defaults);
86 else {
87 PyErr_SetString(PyExc_SystemError, "non-tuple default args");
88 return -1;
90 Py_XDECREF(((PyFunctionObject *) op) -> func_defaults);
91 ((PyFunctionObject *) op) -> func_defaults = defaults;
92 return 0;
95 PyObject *
96 PyFunction_GetClosure(PyObject *op)
98 if (!PyFunction_Check(op)) {
99 PyErr_BadInternalCall();
100 return NULL;
102 return ((PyFunctionObject *) op) -> func_closure;
106 PyFunction_SetClosure(PyObject *op, PyObject *closure)
108 if (!PyFunction_Check(op)) {
109 PyErr_BadInternalCall();
110 return -1;
112 if (closure == Py_None)
113 closure = NULL;
114 else if (PyTuple_Check(closure)) {
115 Py_XINCREF(closure);
117 else {
118 PyErr_SetString(PyExc_SystemError, "non-tuple closure");
119 return -1;
121 Py_XDECREF(((PyFunctionObject *) op) -> func_closure);
122 ((PyFunctionObject *) op) -> func_closure = closure;
123 return 0;
126 /* Methods */
128 #define OFF(x) offsetof(PyFunctionObject, x)
130 #define RR ()
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 */
144 static int
145 restricted(void)
147 if (!PyEval_GetRestricted())
148 return 0;
149 PyErr_SetString(PyExc_RuntimeError,
150 "function attributes not accessible in restricted mode");
151 return 1;
154 static PyObject *
155 func_get_dict(PyFunctionObject *op)
157 if (restricted())
158 return NULL;
159 if (op->func_dict == NULL) {
160 op->func_dict = PyDict_New();
161 if (op->func_dict == NULL)
162 return NULL;
164 Py_INCREF(op->func_dict);
165 return op->func_dict;
168 static int
169 func_set_dict(PyFunctionObject *op, PyObject *value)
171 PyObject *tmp;
173 if (restricted())
174 return -1;
175 /* It is illegal to del f.func_dict */
176 if (value == NULL) {
177 PyErr_SetString(PyExc_TypeError,
178 "function's dictionary may not be deleted");
179 return -1;
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");
185 return -1;
187 tmp = op->func_dict;
188 Py_INCREF(value);
189 op->func_dict = value;
190 Py_XDECREF(tmp);
191 return 0;
194 static PyObject *
195 func_get_code(PyFunctionObject *op)
197 if (restricted())
198 return NULL;
199 Py_INCREF(op->func_code);
200 return op->func_code;
203 static int
204 func_set_code(PyFunctionObject *op, PyObject *value)
206 PyObject *tmp;
208 if (restricted())
209 return -1;
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");
215 return -1;
217 tmp = op->func_code;
218 Py_INCREF(value);
219 op->func_code = value;
220 Py_DECREF(tmp);
221 return 0;
224 static PyObject *
225 func_get_defaults(PyFunctionObject *op)
227 if (restricted())
228 return NULL;
229 if (op->func_defaults == NULL) {
230 Py_INCREF(Py_None);
231 return Py_None;
233 Py_INCREF(op->func_defaults);
234 return op->func_defaults;
237 static int
238 func_set_defaults(PyFunctionObject *op, PyObject *value)
240 PyObject *tmp;
242 if (restricted())
243 return -1;
244 /* Legal to del f.func_defaults.
245 * Can only set func_defaults to NULL or a tuple. */
246 if (value == Py_None)
247 value = NULL;
248 if (value != NULL && !PyTuple_Check(value)) {
249 PyErr_SetString(PyExc_TypeError,
250 "func_defaults must be set to a tuple object");
251 return -1;
253 tmp = op->func_defaults;
254 Py_XINCREF(value);
255 op->func_defaults = value;
256 Py_XDECREF(tmp);
257 return 0;
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 static void
270 func_dealloc(PyFunctionObject *op)
272 _PyObject_GC_UNTRACK(op);
273 if (op->func_weakreflist != NULL)
274 PyObject_ClearWeakRefs((PyObject *) op);
275 Py_DECREF(op->func_code);
276 Py_DECREF(op->func_globals);
277 Py_DECREF(op->func_name);
278 Py_XDECREF(op->func_defaults);
279 Py_XDECREF(op->func_doc);
280 Py_XDECREF(op->func_dict);
281 Py_XDECREF(op->func_closure);
282 PyObject_GC_Del(op);
285 static PyObject*
286 func_repr(PyFunctionObject *op)
288 if (op->func_name == Py_None)
289 return PyString_FromFormat("<anonymous function at %p>", op);
290 return PyString_FromFormat("<function %s at %p>",
291 PyString_AsString(op->func_name),
292 op);
295 static int
296 func_traverse(PyFunctionObject *f, visitproc visit, void *arg)
298 int err;
299 if (f->func_code) {
300 err = visit(f->func_code, arg);
301 if (err)
302 return err;
304 if (f->func_globals) {
305 err = visit(f->func_globals, arg);
306 if (err)
307 return err;
309 if (f->func_defaults) {
310 err = visit(f->func_defaults, arg);
311 if (err)
312 return err;
314 if (f->func_doc) {
315 err = visit(f->func_doc, arg);
316 if (err)
317 return err;
319 if (f->func_name) {
320 err = visit(f->func_name, arg);
321 if (err)
322 return err;
324 if (f->func_dict) {
325 err = visit(f->func_dict, arg);
326 if (err)
327 return err;
329 if (f->func_closure) {
330 err = visit(f->func_closure, arg);
331 if (err)
332 return err;
334 return 0;
337 static PyObject *
338 function_call(PyObject *func, PyObject *arg, PyObject *kw)
340 PyObject *result;
341 PyObject *argdefs;
342 PyObject **d, **k;
343 int nk, nd;
345 argdefs = PyFunction_GET_DEFAULTS(func);
346 if (argdefs != NULL && PyTuple_Check(argdefs)) {
347 d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0);
348 nd = PyTuple_Size(argdefs);
350 else {
351 d = NULL;
352 nd = 0;
355 if (kw != NULL && PyDict_Check(kw)) {
356 int pos, i;
357 nk = PyDict_Size(kw);
358 k = PyMem_NEW(PyObject *, 2*nk);
359 if (k == NULL) {
360 PyErr_NoMemory();
361 return NULL;
363 pos = i = 0;
364 while (PyDict_Next(kw, &pos, &k[i], &k[i+1]))
365 i += 2;
366 nk = i/2;
367 /* XXX This is broken if the caller deletes dict items! */
369 else {
370 k = NULL;
371 nk = 0;
374 result = PyEval_EvalCodeEx(
375 (PyCodeObject *)PyFunction_GET_CODE(func),
376 PyFunction_GET_GLOBALS(func), (PyObject *)NULL,
377 &PyTuple_GET_ITEM(arg, 0), PyTuple_Size(arg),
378 k, nk, d, nd,
379 PyFunction_GET_CLOSURE(func));
381 if (k != NULL)
382 PyMem_DEL(k);
384 return result;
387 /* Bind a function to an object */
388 static PyObject *
389 func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
391 if (obj == Py_None)
392 obj = NULL;
393 return PyMethod_New(func, obj, type);
396 PyTypeObject PyFunction_Type = {
397 PyObject_HEAD_INIT(&PyType_Type)
399 "function",
400 sizeof(PyFunctionObject),
402 (destructor)func_dealloc, /* tp_dealloc */
403 0, /* tp_print */
404 0, /* tp_getattr */
405 0, /* tp_setattr */
406 0, /* tp_compare */
407 (reprfunc)func_repr, /* tp_repr */
408 0, /* tp_as_number */
409 0, /* tp_as_sequence */
410 0, /* tp_as_mapping */
411 0, /* tp_hash */
412 function_call, /* tp_call */
413 0, /* tp_str */
414 PyObject_GenericGetAttr, /* tp_getattro */
415 PyObject_GenericSetAttr, /* tp_setattro */
416 0, /* tp_as_buffer */
417 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
418 0, /* tp_doc */
419 (traverseproc)func_traverse, /* tp_traverse */
420 0, /* tp_clear */
421 0, /* tp_richcompare */
422 offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
423 0, /* tp_iter */
424 0, /* tp_iternext */
425 0, /* tp_methods */
426 func_memberlist, /* tp_members */
427 func_getsetlist, /* tp_getset */
428 0, /* tp_base */
429 0, /* tp_dict */
430 func_descr_get, /* tp_descr_get */
431 0, /* tp_descr_set */
432 offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */
436 /* Class method object */
438 /* A class method receives the class as implicit first argument,
439 just like an instance method receives the instance.
440 To declare a class method, use this idiom:
442 class C:
443 def f(cls, arg1, arg2, ...): ...
444 f = classmethod(f)
446 It can be called either on the class (e.g. C.f()) or on an instance
447 (e.g. C().f()); the instance is ignored except for its class.
448 If a class method is called for a derived class, the derived class
449 object is passed as the implied first argument.
451 Class methods are different than C++ or Java static methods.
452 If you want those, see static methods below.
455 typedef struct {
456 PyObject_HEAD
457 PyObject *cm_callable;
458 } classmethod;
460 static void
461 cm_dealloc(classmethod *cm)
463 Py_XDECREF(cm->cm_callable);
464 cm->ob_type->tp_free((PyObject *)cm);
467 static PyObject *
468 cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
470 classmethod *cm = (classmethod *)self;
472 if (cm->cm_callable == NULL) {
473 PyErr_SetString(PyExc_RuntimeError,
474 "uninitialized classmethod object");
475 return NULL;
477 if (type == NULL)
478 type = (PyObject *)(obj->ob_type);
479 return PyMethod_New(cm->cm_callable,
480 type, (PyObject *)(type->ob_type));
483 static int
484 cm_init(PyObject *self, PyObject *args, PyObject *kwds)
486 classmethod *cm = (classmethod *)self;
487 PyObject *callable;
489 if (!PyArg_ParseTuple(args, "O:callable", &callable))
490 return -1;
491 Py_INCREF(callable);
492 cm->cm_callable = callable;
493 return 0;
496 static char classmethod_doc[] =
497 "classmethod(function) -> method\n\
499 Convert a function to be a class method.\n\
501 A class method receives the class as implicit first argument,\n\
502 just like an instance method receives the instance.\n\
503 To declare a class method, use this idiom:\n\
505 class C:\n\
506 def f(cls, arg1, arg2, ...): ...\n\
507 f = classmethod(f)\n\
509 It can be called either on the class (e.g. C.f()) or on an instance\n\
510 (e.g. C().f()). The instance is ignored except for its class.\n\
511 If a class method is called for a derived class, the derived class\n\
512 object is passed as the implied first argument.\n\
514 Class methods are different than C++ or Java static methods.\n\
515 If you want those, see the staticmethod builtin.";
517 PyTypeObject PyClassMethod_Type = {
518 PyObject_HEAD_INIT(&PyType_Type)
520 "classmethod",
521 sizeof(classmethod),
523 (destructor)cm_dealloc, /* tp_dealloc */
524 0, /* tp_print */
525 0, /* tp_getattr */
526 0, /* tp_setattr */
527 0, /* tp_compare */
528 0, /* tp_repr */
529 0, /* tp_as_number */
530 0, /* tp_as_sequence */
531 0, /* tp_as_mapping */
532 0, /* tp_hash */
533 0, /* tp_call */
534 0, /* tp_str */
535 PyObject_GenericGetAttr, /* tp_getattro */
536 0, /* tp_setattro */
537 0, /* tp_as_buffer */
538 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
539 classmethod_doc, /* tp_doc */
540 0, /* tp_traverse */
541 0, /* tp_clear */
542 0, /* tp_richcompare */
543 0, /* tp_weaklistoffset */
544 0, /* tp_iter */
545 0, /* tp_iternext */
546 0, /* tp_methods */
547 0, /* tp_members */
548 0, /* tp_getset */
549 0, /* tp_base */
550 0, /* tp_dict */
551 cm_descr_get, /* tp_descr_get */
552 0, /* tp_descr_set */
553 0, /* tp_dictoffset */
554 cm_init, /* tp_init */
555 PyType_GenericAlloc, /* tp_alloc */
556 PyType_GenericNew, /* tp_new */
557 _PyObject_Del, /* tp_free */
560 PyObject *
561 PyClassMethod_New(PyObject *callable)
563 classmethod *cm = (classmethod *)
564 PyType_GenericAlloc(&PyClassMethod_Type, 0);
565 if (cm != NULL) {
566 Py_INCREF(callable);
567 cm->cm_callable = callable;
569 return (PyObject *)cm;
573 /* Static method object */
575 /* A static method does not receive an implicit first argument.
576 To declare a static method, use this idiom:
578 class C:
579 def f(arg1, arg2, ...): ...
580 f = staticmethod(f)
582 It can be called either on the class (e.g. C.f()) or on an instance
583 (e.g. C().f()); the instance is ignored except for its class.
585 Static methods in Python are similar to those found in Java or C++.
586 For a more advanced concept, see class methods above.
589 typedef struct {
590 PyObject_HEAD
591 PyObject *sm_callable;
592 } staticmethod;
594 static void
595 sm_dealloc(staticmethod *sm)
597 Py_XDECREF(sm->sm_callable);
598 sm->ob_type->tp_free((PyObject *)sm);
601 static PyObject *
602 sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
604 staticmethod *sm = (staticmethod *)self;
606 if (sm->sm_callable == NULL) {
607 PyErr_SetString(PyExc_RuntimeError,
608 "uninitialized staticmethod object");
609 return NULL;
611 Py_INCREF(sm->sm_callable);
612 return sm->sm_callable;
615 static int
616 sm_init(PyObject *self, PyObject *args, PyObject *kwds)
618 staticmethod *sm = (staticmethod *)self;
619 PyObject *callable;
621 if (!PyArg_ParseTuple(args, "O:callable", &callable))
622 return -1;
623 Py_INCREF(callable);
624 sm->sm_callable = callable;
625 return 0;
628 static char staticmethod_doc[] =
629 "staticmethod(function) -> method\n\
631 Convert a function to be a static method.\n\
633 A static method does not receive an implicit first argument.\n\
634 To declare a static method, use this idiom:\n\
636 class C:\n\
637 def f(arg1, arg2, ...): ...\n\
638 f = staticmethod(f)\n\
640 It can be called either on the class (e.g. C.f()) or on an instance\n\
641 (e.g. C().f()). The instance is ignored except for its class.\n\
643 Static methods in Python are similar to those found in Java or C++.\n\
644 For a more advanced concept, see the classmethod builtin.";
646 PyTypeObject PyStaticMethod_Type = {
647 PyObject_HEAD_INIT(&PyType_Type)
649 "staticmethod",
650 sizeof(staticmethod),
652 (destructor)sm_dealloc, /* tp_dealloc */
653 0, /* tp_print */
654 0, /* tp_getattr */
655 0, /* tp_setattr */
656 0, /* tp_compare */
657 0, /* tp_repr */
658 0, /* tp_as_number */
659 0, /* tp_as_sequence */
660 0, /* tp_as_mapping */
661 0, /* tp_hash */
662 0, /* tp_call */
663 0, /* tp_str */
664 PyObject_GenericGetAttr, /* tp_getattro */
665 0, /* tp_setattro */
666 0, /* tp_as_buffer */
667 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
668 staticmethod_doc, /* tp_doc */
669 0, /* tp_traverse */
670 0, /* tp_clear */
671 0, /* tp_richcompare */
672 0, /* tp_weaklistoffset */
673 0, /* tp_iter */
674 0, /* tp_iternext */
675 0, /* tp_methods */
676 0, /* tp_members */
677 0, /* tp_getset */
678 0, /* tp_base */
679 0, /* tp_dict */
680 sm_descr_get, /* tp_descr_get */
681 0, /* tp_descr_set */
682 0, /* tp_dictoffset */
683 sm_init, /* tp_init */
684 PyType_GenericAlloc, /* tp_alloc */
685 PyType_GenericNew, /* tp_new */
686 _PyObject_Del, /* tp_free */
689 PyObject *
690 PyStaticMethod_New(PyObject *callable)
692 staticmethod *sm = (staticmethod *)
693 PyType_GenericAlloc(&PyStaticMethod_Type, 0);
694 if (sm != NULL) {
695 Py_INCREF(callable);
696 sm->sm_callable = callable;
698 return (PyObject *)sm;