funcobject.c 18.8 KB
Newer Older
1

Guido van Rossum's avatar
Guido van Rossum committed
2 3
/* Function object implementation */

4
#include "Python.h"
5
#include "compile.h"
6
#include "eval.h"
Guido van Rossum's avatar
Guido van Rossum committed
7
#include "structmember.h"
Guido van Rossum's avatar
Guido van Rossum committed
8

9
PyObject *
10
PyFunction_New(PyObject *code, PyObject *globals)
Guido van Rossum's avatar
Guido van Rossum committed
11
{
Neil Schemenauer's avatar
Neil Schemenauer committed
12
	PyFunctionObject *op = PyObject_GC_New(PyFunctionObject,
13
					    &PyFunction_Type);
Guido van Rossum's avatar
Guido van Rossum committed
14
	if (op != NULL) {
15 16
		PyObject *doc;
		PyObject *consts;
17
		op->func_weakreflist = NULL;
18
		Py_INCREF(code);
19
		op->func_code = code;
20
		Py_INCREF(globals);
Guido van Rossum's avatar
Guido van Rossum committed
21
		op->func_globals = globals;
22 23
		op->func_name = ((PyCodeObject *)code)->co_name;
		Py_INCREF(op->func_name);
24
		op->func_defaults = NULL; /* No default arguments */
Jeremy Hylton's avatar
Jeremy Hylton committed
25
		op->func_closure = NULL;
26 27 28
		consts = ((PyCodeObject *)code)->co_consts;
		if (PyTuple_Size(consts) >= 1) {
			doc = PyTuple_GetItem(consts, 0);
Guido van Rossum's avatar
Guido van Rossum committed
29
			if (!PyString_Check(doc) && !PyUnicode_Check(doc))
30
				doc = Py_None;
31 32
		}
		else
33 34
			doc = Py_None;
		Py_INCREF(doc);
35
		op->func_doc = doc;
36
		op->func_dict = NULL;
Guido van Rossum's avatar
Guido van Rossum committed
37
	}
38 39
	else
		return NULL;
Neil Schemenauer's avatar
Neil Schemenauer committed
40
	_PyObject_GC_TRACK(op);
41
	return (PyObject *)op;
Guido van Rossum's avatar
Guido van Rossum committed
42 43
}

44
PyObject *
45
PyFunction_GetCode(PyObject *op)
Guido van Rossum's avatar
Guido van Rossum committed
46
{
47 48
	if (!PyFunction_Check(op)) {
		PyErr_BadInternalCall();
Guido van Rossum's avatar
Guido van Rossum committed
49 50
		return NULL;
	}
51
	return ((PyFunctionObject *) op) -> func_code;
Guido van Rossum's avatar
Guido van Rossum committed
52 53
}

54
PyObject *
55
PyFunction_GetGlobals(PyObject *op)
Guido van Rossum's avatar
Guido van Rossum committed
56
{
57 58
	if (!PyFunction_Check(op)) {
		PyErr_BadInternalCall();
Guido van Rossum's avatar
Guido van Rossum committed
59 60
		return NULL;
	}
61
	return ((PyFunctionObject *) op) -> func_globals;
Guido van Rossum's avatar
Guido van Rossum committed
62 63
}

64
PyObject *
65
PyFunction_GetDefaults(PyObject *op)
66
{
67 68
	if (!PyFunction_Check(op)) {
		PyErr_BadInternalCall();
69 70
		return NULL;
	}
71
	return ((PyFunctionObject *) op) -> func_defaults;
72 73 74
}

int
75
PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
76
{
77 78
	if (!PyFunction_Check(op)) {
		PyErr_BadInternalCall();
79 80
		return -1;
	}
81
	if (defaults == Py_None)
82
		defaults = NULL;
83
	else if (PyTuple_Check(defaults)) {
84
		Py_XINCREF(defaults);
85
	}
86
	else {
87
		PyErr_SetString(PyExc_SystemError, "non-tuple default args");
88 89
		return -1;
	}
90 91
	Py_XDECREF(((PyFunctionObject *) op) -> func_defaults);
	((PyFunctionObject *) op) -> func_defaults = defaults;
92 93 94
	return 0;
}

Jeremy Hylton's avatar
Jeremy Hylton committed
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
PyObject *
PyFunction_GetClosure(PyObject *op)
{
	if (!PyFunction_Check(op)) {
		PyErr_BadInternalCall();
		return NULL;
	}
	return ((PyFunctionObject *) op) -> func_closure;
}

int
PyFunction_SetClosure(PyObject *op, PyObject *closure)
{
	if (!PyFunction_Check(op)) {
		PyErr_BadInternalCall();
		return -1;
	}
	if (closure == Py_None)
		closure = NULL;
	else if (PyTuple_Check(closure)) {
		Py_XINCREF(closure);
	}
	else {
		PyErr_SetString(PyExc_SystemError, "non-tuple closure");
		return -1;
	}
	Py_XDECREF(((PyFunctionObject *) op) -> func_closure);
	((PyFunctionObject *) op) -> func_closure = closure;
	return 0;
}

Guido van Rossum's avatar
Guido van Rossum committed
126 127
/* Methods */

128
#define OFF(x) offsetof(PyFunctionObject, x)
Guido van Rossum's avatar
Guido van Rossum committed
129

130 131
#define RR ()

132
static PyMemberDef func_memberlist[] = {
133 134 135 136 137 138
        {"func_closure",  T_OBJECT,     OFF(func_closure),
	 RESTRICTED|READONLY},
        {"func_doc",      T_OBJECT,     OFF(func_doc), WRITE_RESTRICTED},
        {"__doc__",       T_OBJECT,     OFF(func_doc), WRITE_RESTRICTED},
        {"func_globals",  T_OBJECT,     OFF(func_globals),
	 RESTRICTED|READONLY},
139 140 141
        {"func_name",     T_OBJECT,     OFF(func_name),         READONLY},
        {"__name__",      T_OBJECT,     OFF(func_name),         READONLY},
        {NULL}  /* Sentinel */
Guido van Rossum's avatar
Guido van Rossum committed
142 143
};

144 145 146 147 148 149 150 151 152 153
static int
restricted(void)
{
	if (!PyEval_GetRestricted())
		return 0;
	PyErr_SetString(PyExc_RuntimeError,
		"function attributes not accessible in restricted mode");
	return 1;
}

154
static PyObject *
155
func_get_dict(PyFunctionObject *op)
Guido van Rossum's avatar
Guido van Rossum committed
156
{
157
	if (restricted())
158
		return NULL;
159 160 161
	if (op->func_dict == NULL) {
		op->func_dict = PyDict_New();
		if (op->func_dict == NULL)
162 163
			return NULL;
	}
164 165
	Py_INCREF(op->func_dict);
	return op->func_dict;
Guido van Rossum's avatar
Guido van Rossum committed
166 167
}

168
static int
169
func_set_dict(PyFunctionObject *op, PyObject *value)
170
{
171
	PyObject *tmp;
172

173 174 175 176 177 178 179 180 181 182 183 184
	if (restricted())
		return -1;
	/* It is illegal to del f.func_dict */
	if (value == NULL) {
		PyErr_SetString(PyExc_TypeError,
				"function's dictionary may not be deleted");
		return -1;
	}
	/* Can only set func_dict to a dictionary */
	if (!PyDict_Check(value)) {
		PyErr_SetString(PyExc_TypeError,
				"setting function's dictionary to a non-dict");
185 186
		return -1;
	}
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
	tmp = op->func_dict;
	Py_INCREF(value);
	op->func_dict = value;
	Py_XDECREF(tmp);
	return 0;
}

static PyObject *
func_get_code(PyFunctionObject *op)
{
	if (restricted())
		return NULL;
	Py_INCREF(op->func_code);
	return op->func_code;
}

static int
func_set_code(PyFunctionObject *op, PyObject *value)
{
	PyObject *tmp;

	if (restricted())
		return -1;
	/* Not legal to del f.func_code or to set it to anything
	 * other than a code object. */
	if (value == NULL || !PyCode_Check(value)) {
		PyErr_SetString(PyExc_TypeError,
214
				"func_code must be set to a code object");
215
		return -1;
216
	}
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
	tmp = op->func_code;
	Py_INCREF(value);
	op->func_code = value;
	Py_DECREF(tmp);
	return 0;
}

static PyObject *
func_get_defaults(PyFunctionObject *op)
{
	if (restricted())
		return NULL;
	if (op->func_defaults == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
232
	}
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
	Py_INCREF(op->func_defaults);
	return op->func_defaults;
}

static int
func_set_defaults(PyFunctionObject *op, PyObject *value)
{
	PyObject *tmp;

	if (restricted())
		return -1;
	/* Legal to del f.func_defaults.
	 * Can only set func_defaults to NULL or a tuple. */
	if (value == Py_None)
		value = NULL;
	if (value != NULL && !PyTuple_Check(value)) {
		PyErr_SetString(PyExc_TypeError,
				"func_defaults must be set to a tuple object");
		return -1;
252
	}
253 254 255 256 257
	tmp = op->func_defaults;
	Py_XINCREF(value);
	op->func_defaults = value;
	Py_XDECREF(tmp);
	return 0;
258 259
}

260
static PyGetSetDef func_getsetlist[] = {
261 262 263 264 265 266 267 268
        {"func_code", (getter)func_get_code, (setter)func_set_code},
        {"func_defaults", (getter)func_get_defaults,
	 (setter)func_set_defaults},
	{"func_dict", (getter)func_get_dict, (setter)func_set_dict},
	{"__dict__", (getter)func_get_dict, (setter)func_set_dict},
	{NULL} /* Sentinel */
};

269
PyDoc_STRVAR(func_doc,
270
"function(code, globals[, name[, argdefs[, closure]]])\n\
271 272 273
\n\
Create a function object from a code object and a dictionary.\n\
The optional name string overrides the name from the code object.\n\
274 275 276 277 278 279 280 281 282 283 284 285
The optional argdefs tuple specifies the default argument values.\n\
The optional closure tuple supplies the bindings for free variables.");

/* func_new() maintains the following invariants for closures.  The
   closure must correspond to the free variables of the code object.
   
   if len(code.co_freevars) == 0: 
           closure = NULL
   else:
           len(closure) == len(code.co_freevars)
   for every elt in closure, type(elt) == cell
*/
286 287 288 289

static PyObject *
func_new(PyTypeObject* type, PyObject* args, PyObject* kw)
{
290
	PyCodeObject *code;
291 292 293
	PyObject *globals;
	PyObject *name = Py_None;
	PyObject *defaults = Py_None;
294
	PyObject *closure = Py_None;
295
	PyFunctionObject *newfunc;
296
	int nfree, nclosure;
297

298
	if (!PyArg_ParseTuple(args, "O!O!|OOO:function",
299 300
			      &PyCode_Type, &code,
			      &PyDict_Type, &globals,
301
			      &name, &defaults, &closure))
302 303 304 305 306 307
		return NULL;
	if (name != Py_None && !PyString_Check(name)) {
		PyErr_SetString(PyExc_TypeError,
				"arg 3 (name) must be None or string");
		return NULL;
	}
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
	if (defaults != Py_None && !PyTuple_Check(defaults)) {
		PyErr_SetString(PyExc_TypeError,
				"arg 4 (defaults) must be None or tuple");
		return NULL;
	}
	nfree = PyTuple_GET_SIZE(code->co_freevars);
	if (!PyTuple_Check(closure)) {
		if (nfree && closure == Py_None) {
			PyErr_SetString(PyExc_TypeError,
					"arg 5 (closure) must be tuple");
			return NULL;
		}
		else if (closure != Py_None) {
			PyErr_SetString(PyExc_TypeError,
				"arg 5 (closure) must be None or tuple");
			return NULL;
		}
	}
326

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
	/* check that the closure is well-formed */
	nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
	if (nfree != nclosure)
		return PyErr_Format(PyExc_ValueError,
				    "%s requires closure of length %d, not %d",
				    PyString_AS_STRING(code->co_name),
				    nfree, nclosure);
	if (nclosure) {
		int i;
		for (i = 0; i < nclosure; i++) {
			PyObject *o = PyTuple_GET_ITEM(closure, i);
			if (!PyCell_Check(o)) {
				return PyErr_Format(PyExc_TypeError,
				    "arg 5 (closure) expected cell, found %s",
						    o->ob_type->tp_name);
			}
		}
	}
	
	newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code, 
						     globals);
348 349
	if (newfunc == NULL)
		return NULL;
350
	
351
	if (name != Py_None) {
352 353
		Py_INCREF(name);
		Py_DECREF(newfunc->func_name);
354 355 356
		newfunc->func_name = name;
	}
	if (defaults != Py_None) {
357
		Py_INCREF(defaults);
358 359
		newfunc->func_defaults  = defaults;
	}
360 361 362 363
	if (closure != Py_None) {
		Py_INCREF(closure);
		newfunc->func_closure = closure;
	}
364 365 366 367

	return (PyObject *)newfunc;
}

Guido van Rossum's avatar
Guido van Rossum committed
368
static void
369
func_dealloc(PyFunctionObject *op)
Guido van Rossum's avatar
Guido van Rossum committed
370
{
Neil Schemenauer's avatar
Neil Schemenauer committed
371
	_PyObject_GC_UNTRACK(op);
372 373
	if (op->func_weakreflist != NULL)
		PyObject_ClearWeakRefs((PyObject *) op);
374 375 376 377 378
	Py_DECREF(op->func_code);
	Py_DECREF(op->func_globals);
	Py_DECREF(op->func_name);
	Py_XDECREF(op->func_defaults);
	Py_XDECREF(op->func_doc);
379
	Py_XDECREF(op->func_dict);
380
	Py_XDECREF(op->func_closure);
Neil Schemenauer's avatar
Neil Schemenauer committed
381
	PyObject_GC_Del(op);
Guido van Rossum's avatar
Guido van Rossum committed
382 383
}

384
static PyObject*
385
func_repr(PyFunctionObject *op)
386
{
387
	if (op->func_name == Py_None)
388 389 390 391
		return PyString_FromFormat("<anonymous function at %p>", op);
	return PyString_FromFormat("<function %s at %p>",
				   PyString_AsString(op->func_name),
				   op);
392 393
}

394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
static int
func_traverse(PyFunctionObject *f, visitproc visit, void *arg)
{
	int err;
	if (f->func_code) {
		err = visit(f->func_code, arg);
		if (err)
			return err;
	}
	if (f->func_globals) {
		err = visit(f->func_globals, arg);
		if (err)
			return err;
	}
	if (f->func_defaults) {
		err = visit(f->func_defaults, arg);
		if (err)
			return err;
	}
	if (f->func_doc) {
		err = visit(f->func_doc, arg);
		if (err)
			return err;
	}
	if (f->func_name) {
		err = visit(f->func_name, arg);
		if (err)
			return err;
	}
423 424 425 426 427
	if (f->func_dict) {
		err = visit(f->func_dict, arg);
		if (err)
			return err;
	}
428 429 430 431 432
	if (f->func_closure) {
		err = visit(f->func_closure, arg);
		if (err)
			return err;
	}
433 434 435
	return 0;
}

436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
static PyObject *
function_call(PyObject *func, PyObject *arg, PyObject *kw)
{
	PyObject *result;
	PyObject *argdefs;
	PyObject **d, **k;
	int nk, nd;

	argdefs = PyFunction_GET_DEFAULTS(func);
	if (argdefs != NULL && PyTuple_Check(argdefs)) {
		d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0);
		nd = PyTuple_Size(argdefs);
	}
	else {
		d = NULL;
		nd = 0;
	}

	if (kw != NULL && PyDict_Check(kw)) {
		int pos, i;
		nk = PyDict_Size(kw);
		k = PyMem_NEW(PyObject *, 2*nk);
		if (k == NULL) {
			PyErr_NoMemory();
			return NULL;
		}
		pos = i = 0;
		while (PyDict_Next(kw, &pos, &k[i], &k[i+1]))
			i += 2;
		nk = i/2;
		/* XXX This is broken if the caller deletes dict items! */
	}
	else {
		k = NULL;
		nk = 0;
	}

	result = PyEval_EvalCodeEx(
		(PyCodeObject *)PyFunction_GET_CODE(func),
		PyFunction_GET_GLOBALS(func), (PyObject *)NULL,
		&PyTuple_GET_ITEM(arg, 0), PyTuple_Size(arg),
		k, nk, d, nd,
		PyFunction_GET_CLOSURE(func));

	if (k != NULL)
		PyMem_DEL(k);

	return result;
}

/* Bind a function to an object */
static PyObject *
func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
{
	if (obj == Py_None)
		obj = NULL;
	return PyMethod_New(func, obj, type);
}

495 496
PyTypeObject PyFunction_Type = {
	PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum's avatar
Guido van Rossum committed
497 498
	0,
	"function",
Neil Schemenauer's avatar
Neil Schemenauer committed
499
	sizeof(PyFunctionObject),
Guido van Rossum's avatar
Guido van Rossum committed
500
	0,
501 502 503 504 505 506 507 508 509 510 511 512
	(destructor)func_dealloc,		/* tp_dealloc */
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
	(reprfunc)func_repr,			/* tp_repr */
	0,					/* tp_as_number */
	0,					/* tp_as_sequence */
	0,					/* tp_as_mapping */
	0,					/* tp_hash */
	function_call,				/* tp_call */
	0,					/* tp_str */
513 514
	PyObject_GenericGetAttr,		/* tp_getattro */
	PyObject_GenericSetAttr,		/* tp_setattro */
515
	0,					/* tp_as_buffer */
Neil Schemenauer's avatar
Neil Schemenauer committed
516
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
517
	func_doc,				/* tp_doc */
518 519 520
	(traverseproc)func_traverse,		/* tp_traverse */
	0,					/* tp_clear */
	0,					/* tp_richcompare */
521
	offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
522 523 524 525
	0,					/* tp_iter */
	0,					/* tp_iternext */
	0,					/* tp_methods */
	func_memberlist,			/* tp_members */
526
	func_getsetlist,			/* tp_getset */
527 528 529 530 531
	0,					/* tp_base */
	0,					/* tp_dict */
	func_descr_get,				/* tp_descr_get */
	0,					/* tp_descr_set */
	offsetof(PyFunctionObject, func_dict),	/* tp_dictoffset */
532 533 534
	0,					/* tp_init */
	0,					/* tp_alloc */
	func_new,				/* tp_new */
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
};


/* Class method object */

/* A class method receives the class as implicit first argument,
   just like an instance method receives the instance.
   To declare a class method, use this idiom:

     class C:
         def f(cls, arg1, arg2, ...): ...
	 f = classmethod(f)
   
   It can be called either on the class (e.g. C.f()) or on an instance
   (e.g. C().f()); the instance is ignored except for its class.
   If a class method is called for a derived class, the derived class
   object is passed as the implied first argument.

   Class methods are different than C++ or Java static methods.
   If you want those, see static methods below.
*/

typedef struct {
	PyObject_HEAD
	PyObject *cm_callable;
} classmethod;

static void
cm_dealloc(classmethod *cm)
{
	Py_XDECREF(cm->cm_callable);
566
	cm->ob_type->tp_free((PyObject *)cm);
567 568 569 570 571 572 573 574 575 576 577 578
}

static PyObject *
cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
{
	classmethod *cm = (classmethod *)self;

	if (cm->cm_callable == NULL) {
		PyErr_SetString(PyExc_RuntimeError,
				"uninitialized classmethod object");
		return NULL;
	}
579 580
	if (type == NULL)
		type = (PyObject *)(obj->ob_type);
581 582 583 584 585 586 587 588 589 590
 	return PyMethod_New(cm->cm_callable,
			    type, (PyObject *)(type->ob_type));
}

static int
cm_init(PyObject *self, PyObject *args, PyObject *kwds)
{
	classmethod *cm = (classmethod *)self;
	PyObject *callable;

591
	if (!PyArg_ParseTuple(args, "O:classmethod", &callable))
592 593 594 595 596 597
		return -1;
	Py_INCREF(callable);
	cm->cm_callable = callable;
	return 0;
}

598
PyDoc_STRVAR(classmethod_doc,
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
"classmethod(function) -> method\n\
\n\
Convert a function to be a class method.\n\
\n\
A class method receives the class as implicit first argument,\n\
just like an instance method receives the instance.\n\
To declare a class method, use this idiom:\n\
\n\
  class C:\n\
      def f(cls, arg1, arg2, ...): ...\n\
      f = classmethod(f)\n\
\n\
It can be called either on the class (e.g. C.f()) or on an instance\n\
(e.g. C().f()).  The instance is ignored except for its class.\n\
If a class method is called for a derived class, the derived class\n\
object is passed as the implied first argument.\n\
615
\n\
616
Class methods are different than C++ or Java static methods.\n\
617
If you want those, see the staticmethod builtin.");
618

619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
PyTypeObject PyClassMethod_Type = {
	PyObject_HEAD_INIT(&PyType_Type)
	0,
	"classmethod",
	sizeof(classmethod),
	0,
	(destructor)cm_dealloc,			/* tp_dealloc */
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
	0,					/* tp_repr */
	0,					/* tp_as_number */
	0,					/* tp_as_sequence */
	0,					/* tp_as_mapping */
	0,					/* tp_hash */
	0,					/* tp_call */
	0,					/* tp_str */
	PyObject_GenericGetAttr,		/* tp_getattro */
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
641
	classmethod_doc,			/* tp_doc */
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
	0,					/* tp_traverse */
	0,					/* tp_clear */
	0,					/* tp_richcompare */
	0,					/* tp_weaklistoffset */
	0,					/* tp_iter */
	0,					/* tp_iternext */
	0,					/* tp_methods */
	0,					/* tp_members */
	0,					/* tp_getset */
	0,					/* tp_base */
	0,					/* tp_dict */
	cm_descr_get,				/* tp_descr_get */
	0,					/* tp_descr_set */
	0,					/* tp_dictoffset */
	cm_init,				/* tp_init */
	PyType_GenericAlloc,			/* tp_alloc */
	PyType_GenericNew,			/* tp_new */
659
	PyObject_Del,		                /* tp_free */
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
};

PyObject *
PyClassMethod_New(PyObject *callable)
{
	classmethod *cm = (classmethod *)
		PyType_GenericAlloc(&PyClassMethod_Type, 0);
	if (cm != NULL) {
		Py_INCREF(callable);
		cm->cm_callable = callable;
	}
	return (PyObject *)cm;
}


/* Static method object */

/* A static method does not receive an implicit first argument.
   To declare a static method, use this idiom:

     class C:
         def f(arg1, arg2, ...): ...
	 f = staticmethod(f)

   It can be called either on the class (e.g. C.f()) or on an instance
   (e.g. C().f()); the instance is ignored except for its class.

   Static methods in Python are similar to those found in Java or C++.
   For a more advanced concept, see class methods above.
*/

typedef struct {
	PyObject_HEAD
	PyObject *sm_callable;
} staticmethod;

static void
sm_dealloc(staticmethod *sm)
{
	Py_XDECREF(sm->sm_callable);
700
	sm->ob_type->tp_free((PyObject *)sm);
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
}

static PyObject *
sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
{
	staticmethod *sm = (staticmethod *)self;

	if (sm->sm_callable == NULL) {
		PyErr_SetString(PyExc_RuntimeError,
				"uninitialized staticmethod object");
		return NULL;
	}
	Py_INCREF(sm->sm_callable);
	return sm->sm_callable;
}

static int
sm_init(PyObject *self, PyObject *args, PyObject *kwds)
{
	staticmethod *sm = (staticmethod *)self;
	PyObject *callable;

723
	if (!PyArg_ParseTuple(args, "O:staticmethod", &callable))
724 725 726 727 728 729
		return -1;
	Py_INCREF(callable);
	sm->sm_callable = callable;
	return 0;
}

730
PyDoc_STRVAR(staticmethod_doc,
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
"staticmethod(function) -> method\n\
\n\
Convert a function to be a static method.\n\
\n\
A static method does not receive an implicit first argument.\n\
To declare a static method, use this idiom:\n\
\n\
     class C:\n\
         def f(arg1, arg2, ...): ...\n\
	 f = staticmethod(f)\n\
\n\
It can be called either on the class (e.g. C.f()) or on an instance\n\
(e.g. C().f()).  The instance is ignored except for its class.\n\
\n\
Static methods in Python are similar to those found in Java or C++.\n\
746
For a more advanced concept, see the classmethod builtin.");
747

748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
PyTypeObject PyStaticMethod_Type = {
	PyObject_HEAD_INIT(&PyType_Type)
	0,
	"staticmethod",
	sizeof(staticmethod),
	0,
	(destructor)sm_dealloc,			/* tp_dealloc */
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
	0,					/* tp_repr */
	0,					/* tp_as_number */
	0,					/* tp_as_sequence */
	0,					/* tp_as_mapping */
	0,					/* tp_hash */
	0,					/* tp_call */
	0,					/* tp_str */
	PyObject_GenericGetAttr,		/* tp_getattro */
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
770
	staticmethod_doc,			/* tp_doc */
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
	0,					/* tp_traverse */
	0,					/* tp_clear */
	0,					/* tp_richcompare */
	0,					/* tp_weaklistoffset */
	0,					/* tp_iter */
	0,					/* tp_iternext */
	0,					/* tp_methods */
	0,					/* tp_members */
	0,					/* tp_getset */
	0,					/* tp_base */
	0,					/* tp_dict */
	sm_descr_get,				/* tp_descr_get */
	0,					/* tp_descr_set */
	0,					/* tp_dictoffset */
	sm_init,				/* tp_init */
	PyType_GenericAlloc,			/* tp_alloc */
	PyType_GenericNew,			/* tp_new */
788
	PyObject_Del,           		/* tp_free */
Guido van Rossum's avatar
Guido van Rossum committed
789
};
790 791 792 793 794 795 796 797 798 799 800 801

PyObject *
PyStaticMethod_New(PyObject *callable)
{
	staticmethod *sm = (staticmethod *)
		PyType_GenericAlloc(&PyStaticMethod_Type, 0);
	if (sm != NULL) {
		Py_INCREF(callable);
		sm->sm_callable = callable;
	}
	return (PyObject *)sm;
}