1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
7 Permission to use, copy, modify, and distribute this software and its
8 documentation for any purpose and without fee is hereby granted,
9 provided that the above copyright notice appear in all copies and that
10 both that copyright notice and this permission notice appear in
11 supporting documentation, and that the names of Stichting Mathematisch
12 Centrum or CWI or Corporation for National Research Initiatives or
13 CNRI not be used in advertising or publicity pertaining to
14 distribution of the software without specific, written prior
17 While CWI is the initial source for this software, a modified version
18 is made available by the Corporation for National Research Initiatives
19 (CNRI) at the Internet address ftp://ftp.python.org.
21 STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22 REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23 MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24 CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25 DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26 PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27 TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28 PERFORMANCE OF THIS SOFTWARE.
30 ******************************************************************/
32 /* Generic object operations; and implementation of None (NoObject) */
36 #if defined( Py_TRACE_REFS ) || defined( Py_REF_DEBUG )
40 /* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
41 These are used by the individual routines for object creation.
42 Do not call them otherwise, they do not initialize the object! */
45 static PyTypeObject
*type_list
;
46 extern int tuple_zero_allocs
, fast_tuple_allocs
;
47 extern int quick_int_allocs
, quick_neg_int_allocs
;
48 extern int null_strings
, one_strings
;
54 for (tp
= type_list
; tp
; tp
= tp
->tp_next
)
55 fprintf(stderr
, "%s alloc'd: %d, freed: %d, max in use: %d\n",
56 tp
->tp_name
, tp
->tp_alloc
, tp
->tp_free
,
58 fprintf(stderr
, "fast tuple allocs: %d, empty: %d\n",
59 fast_tuple_allocs
, tuple_zero_allocs
);
60 fprintf(stderr
, "fast int allocs: pos: %d, neg: %d\n",
61 quick_int_allocs
, quick_neg_int_allocs
);
62 fprintf(stderr
, "null strings: %d, 1-strings: %d\n",
63 null_strings
, one_strings
);
73 result
= PyList_New(0);
76 for (tp
= type_list
; tp
; tp
= tp
->tp_next
) {
77 v
= Py_BuildValue("(siii)", tp
->tp_name
, tp
->tp_alloc
,
78 tp
->tp_free
, tp
->tp_maxalloc
);
83 if (PyList_Append(result
, v
) < 0) {
97 if (tp
->tp_alloc
== 0) {
98 /* first time; insert in linked list */
99 if (tp
->tp_next
!= NULL
) /* sanity check */
100 Py_FatalError("XXX inc_count sanity check");
101 tp
->tp_next
= type_list
;
105 if (tp
->tp_alloc
- tp
->tp_free
> tp
->tp_maxalloc
)
106 tp
->tp_maxalloc
= tp
->tp_alloc
- tp
->tp_free
;
122 PyObject
*op
= (PyObject
*) malloc(tp
->tp_basicsize
);
125 return PyErr_NoMemory();
127 _Py_NewReference(op
);
133 _PyObject_NewVar(tp
, size
)
138 _PyObject_NewVar(tp
, size
, op
)
145 PyVarObject
*op
= (PyVarObject
*)
146 malloc(tp
->tp_basicsize
+ size
* tp
->tp_itemsize
);
149 return (PyVarObject
*)PyErr_NoMemory();
152 _Py_NewReference(op
);
157 PyObject_Print(op
, fp
, flags
)
163 if (PyErr_CheckSignals())
165 #ifdef USE_STACKCHECK
166 if (PyOS_CheckStack()) {
167 PyErr_SetString(PyExc_MemoryError
, "Stack overflow");
172 fprintf(fp
, "<nil>");
175 if (op
->ob_refcnt
<= 0)
176 fprintf(fp
, "<refcnt %u at %lx>",
177 op
->ob_refcnt
, (long)op
);
178 else if (op
->ob_type
->tp_print
== NULL
) {
179 if (op
->ob_type
->tp_repr
== NULL
) {
180 fprintf(fp
, "<%s object at %lx>",
181 op
->ob_type
->tp_name
, (long)op
);
185 if (flags
& Py_PRINT_RAW
)
186 s
= PyObject_Str(op
);
188 s
= PyObject_Repr(op
);
191 else if (!PyString_Check(s
)) {
192 PyErr_SetString(PyExc_TypeError
,
197 ret
= PyObject_Print(s
, fp
,
204 ret
= (*op
->ob_type
->tp_print
)(op
, fp
, flags
);
208 PyErr_SetFromErrno(PyExc_IOError
);
220 if (PyErr_CheckSignals())
222 #ifdef USE_STACKCHECK
223 if (PyOS_CheckStack()) {
224 PyErr_SetString(PyExc_MemoryError
, "Stack overflow");
229 return PyString_FromString("<NULL>");
230 else if (v
->ob_type
->tp_repr
== NULL
) {
232 sprintf(buf
, "<%.80s object at %lx>",
233 v
->ob_type
->tp_name
, (long)v
);
234 return PyString_FromString(buf
);
237 return (*v
->ob_type
->tp_repr
)(v
);
245 return PyString_FromString("<NULL>");
246 else if (PyString_Check(v
)) {
250 else if (v
->ob_type
->tp_str
!= NULL
)
251 return (*v
->ob_type
->tp_str
)(v
);
255 if (!PyInstance_Check(v
) ||
256 (func
= PyObject_GetAttrString(v
, "__str__")) == NULL
) {
258 return PyObject_Repr(v
);
260 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
271 /* __rcmp__ actually won't be called unless __cmp__ isn't defined,
272 because the check in cmpobject() reverses the objects first.
273 This is intentional -- it makes no sense to define cmp(x,y)
274 different than -cmp(y,x). */
275 if (PyInstance_Check(v
) || PyInstance_Check(w
))
276 return PyInstance_DoBinOp(v
, w
, "__cmp__", "__rcmp__", do_cmp
);
277 c
= PyObject_Compare(v
, w
);
278 if (c
&& PyErr_Occurred())
280 return PyInt_FromLong(c
);
284 PyObject_Compare(v
, w
)
287 PyTypeObject
*vtp
, *wtp
;
288 if (v
== NULL
|| w
== NULL
) {
289 PyErr_BadInternalCall();
294 if (PyInstance_Check(v
) || PyInstance_Check(w
)) {
297 if (!PyInstance_Check(v
))
298 return -PyObject_Compare(w
, v
);
302 if (!PyInt_Check(res
)) {
304 PyErr_SetString(PyExc_TypeError
,
305 "comparison did not return an int");
308 c
= PyInt_AsLong(res
);
310 return (c
< 0) ? -1 : (c
> 0) ? 1 : 0;
312 if ((vtp
= v
->ob_type
) != (wtp
= w
->ob_type
)) {
313 char *vname
= vtp
->tp_name
;
314 char *wname
= wtp
->tp_name
;
315 if (vtp
->tp_as_number
!= NULL
&& wtp
->tp_as_number
!= NULL
) {
317 err
= PyNumber_CoerceEx(&v
, &w
);
323 if (vtp
->tp_compare
== NULL
)
324 cmp
= (v
< w
) ? -1 : 1;
326 cmp
= (*vtp
->tp_compare
)(v
, w
);
332 else if (vtp
->tp_as_number
!= NULL
)
334 else if (wtp
->tp_as_number
!= NULL
)
336 /* Numerical types compare smaller than all other types */
337 return strcmp(vname
, wname
);
339 if (vtp
->tp_compare
== NULL
)
340 return (v
< w
) ? -1 : 1;
341 return (*vtp
->tp_compare
)(v
, w
);
348 PyTypeObject
*tp
= v
->ob_type
;
349 if (tp
->tp_hash
!= NULL
)
350 return (*tp
->tp_hash
)(v
);
351 if (tp
->tp_compare
== NULL
)
352 return (long) v
; /* Use address as hash value */
353 /* If there's a cmp but no hash defined, the object can't be hashed */
354 PyErr_SetString(PyExc_TypeError
, "unhashable type");
359 PyObject_GetAttrString(v
, name
)
363 if (v
->ob_type
->tp_getattro
!= NULL
) {
365 w
= PyString_InternFromString(name
);
368 res
= (*v
->ob_type
->tp_getattro
)(v
, w
);
373 if (v
->ob_type
->tp_getattr
== NULL
) {
374 PyErr_Format(PyExc_AttributeError
,
375 "'%.50s' object has no attribute '%.400s'",
381 return (*v
->ob_type
->tp_getattr
)(v
, name
);
386 PyObject_HasAttrString(v
, name
)
390 PyObject
*res
= PyObject_GetAttrString(v
, name
);
400 PyObject_SetAttrString(v
, name
, w
)
405 if (v
->ob_type
->tp_setattro
!= NULL
) {
408 s
= PyString_InternFromString(name
);
411 res
= (*v
->ob_type
->tp_setattro
)(v
, s
, w
);
416 if (v
->ob_type
->tp_setattr
== NULL
) {
417 if (v
->ob_type
->tp_getattr
== NULL
)
418 PyErr_SetString(PyExc_TypeError
,
419 "attribute-less object (assign or del)");
421 PyErr_SetString(PyExc_TypeError
,
422 "object has read-only attributes");
426 return (*v
->ob_type
->tp_setattr
)(v
, name
, w
);
431 PyObject_GetAttr(v
, name
)
435 if (v
->ob_type
->tp_getattro
!= NULL
)
436 return (*v
->ob_type
->tp_getattro
)(v
, name
);
438 return PyObject_GetAttrString(v
, PyString_AsString(name
));
442 PyObject_HasAttr(v
, name
)
446 PyObject
*res
= PyObject_GetAttr(v
, name
);
456 PyObject_SetAttr(v
, name
, value
)
463 PyString_InternInPlace(&name
);
464 if (v
->ob_type
->tp_setattro
!= NULL
)
465 err
= (*v
->ob_type
->tp_setattro
)(v
, name
, value
);
467 err
= PyObject_SetAttrString(
468 v
, PyString_AsString(name
), value
);
473 /* Test a value used as condition, e.g., in a for or if statement.
474 Return -1 if an error occurred */
483 else if (v
->ob_type
->tp_as_number
!= NULL
&&
484 v
->ob_type
->tp_as_number
->nb_nonzero
!= NULL
)
485 res
= (*v
->ob_type
->tp_as_number
->nb_nonzero
)(v
);
486 else if (v
->ob_type
->tp_as_mapping
!= NULL
&&
487 v
->ob_type
->tp_as_mapping
->mp_length
!= NULL
)
488 res
= (*v
->ob_type
->tp_as_mapping
->mp_length
)(v
);
489 else if (v
->ob_type
->tp_as_sequence
!= NULL
&&
490 v
->ob_type
->tp_as_sequence
->sq_length
!= NULL
)
491 res
= (*v
->ob_type
->tp_as_sequence
->sq_length
)(v
);
499 /* equivalent of 'not v'
500 Return -1 if an error occurred */
507 res
= PyObject_IsTrue(v
);
513 /* Coerce two numeric types to the "larger" one.
514 Increment the reference count on each argument.
515 Return -1 and raise an exception if no coercion is possible
516 (and then no reference count is incremented).
520 PyNumber_CoerceEx(pv
, pw
)
523 register PyObject
*v
= *pv
;
524 register PyObject
*w
= *pw
;
527 if (v
->ob_type
== w
->ob_type
&& !PyInstance_Check(v
)) {
532 if (v
->ob_type
->tp_as_number
&& v
->ob_type
->tp_as_number
->nb_coerce
) {
533 res
= (*v
->ob_type
->tp_as_number
->nb_coerce
)(pv
, pw
);
537 if (w
->ob_type
->tp_as_number
&& w
->ob_type
->tp_as_number
->nb_coerce
) {
538 res
= (*w
->ob_type
->tp_as_number
->nb_coerce
)(pw
, pv
);
546 PyNumber_Coerce(pv
, pw
)
549 int err
= PyNumber_CoerceEx(pv
, pw
);
552 PyErr_SetString(PyExc_TypeError
, "number coercion failed");
557 /* Test whether an object can be called */
565 if (x
->ob_type
->tp_call
!= NULL
||
566 PyFunction_Check(x
) ||
568 PyCFunction_Check(x
) ||
571 if (PyInstance_Check(x
)) {
572 PyObject
*call
= PyObject_GetAttrString(x
, "__call__");
577 /* Could test recursively but don't, for fear of endless
578 recursion if some joker sets self.__call__ = self */
587 NoObject is usable as a non-NULL undefined value, used by the macro None.
588 There is (and should be!) no way to create other objects of this type,
589 so there is exactly one (which is indestructible, by the way).
597 return PyString_FromString("None");
600 static PyTypeObject PyNothing_Type
= {
601 PyObject_HEAD_INIT(&PyType_Type
)
606 0, /*tp_dealloc*/ /*never called*/
611 (reprfunc
)none_repr
, /*tp_repr*/
613 0, /*tp_as_sequence*/
618 PyObject _Py_NoneStruct
= {
619 PyObject_HEAD_INIT(&PyNothing_Type
)
625 static PyObject refchain
= {&refchain
, &refchain
};
628 _Py_ResetReferences()
630 refchain
._ob_prev
= refchain
._ob_next
= &refchain
;
640 op
->_ob_next
= refchain
._ob_next
;
641 op
->_ob_prev
= &refchain
;
642 refchain
._ob_next
->_ob_prev
= op
;
643 refchain
._ob_next
= op
;
645 inc_count(op
->ob_type
);
650 _Py_ForgetReference(op
)
651 register PyObject
*op
;
653 register PyObject
*p
;
654 if (op
->ob_refcnt
< 0)
655 Py_FatalError("UNREF negative refcnt");
656 if (op
== &refchain
||
657 op
->_ob_prev
->_ob_next
!= op
|| op
->_ob_next
->_ob_prev
!= op
)
658 Py_FatalError("UNREF invalid object");
659 #ifdef SLOW_UNREF_CHECK
660 for (p
= refchain
._ob_next
; p
!= &refchain
; p
= p
->_ob_next
) {
664 if (p
== &refchain
) /* Not found */
665 Py_FatalError("UNREF unknown object");
667 op
->_ob_next
->_ob_prev
= op
->_ob_prev
;
668 op
->_ob_prev
->_ob_next
= op
->_ob_next
;
669 op
->_ob_next
= op
->_ob_prev
= NULL
;
671 op
->ob_type
->tp_free
++;
679 destructor dealloc
= op
->ob_type
->tp_dealloc
;
680 _Py_ForgetReference(op
);
686 _Py_PrintReferences(fp
)
690 fprintf(fp
, "Remaining objects:\n");
691 for (op
= refchain
._ob_next
; op
!= &refchain
; op
= op
->_ob_next
) {
692 fprintf(fp
, "[%d] ", op
->ob_refcnt
);
693 if (PyObject_Print(op
, fp
, 0) != 0)
700 _Py_GetObjects(self
, args
)
708 if (!PyArg_ParseTuple(args
, "i|O", &n
, &t
))
710 op
= refchain
._ob_next
;
714 for (i
= 0; (n
== 0 || i
< n
) && op
!= &refchain
; i
++) {
715 while (op
== self
|| op
== args
|| op
== res
|| op
== t
||
716 t
!= NULL
&& op
->ob_type
!= (PyTypeObject
*) t
) {
721 if (PyList_Append(res
, op
) < 0) {
733 /* Hack to force loading of cobject.o */
734 PyTypeObject
*_Py_cobject_hack
= &PyCObject_Type
;
737 /* Hack to force loading of abstract.o */
738 int (*_Py_abstract_hack
) Py_FPROTO((PyObject
*)) = &PyObject_Length
;
741 /* Malloc wrappers (see mymalloc.h) */
743 /* The Py_{Malloc,Realloc} wrappers call PyErr_NoMemory() on failure */
752 nbytes
= _PyMem_EXTRA
;
764 Py_Realloc(p
, nbytes
)
770 nbytes
= _PyMem_EXTRA
;
772 p
= realloc(p
, nbytes
);
788 /* The PyMem_{Malloc,Realloc} wrappers don't call anything on failure */
796 nbytes
= _PyMem_EXTRA
;
798 return malloc(nbytes
);
802 PyMem_Realloc(p
, nbytes
)
808 nbytes
= _PyMem_EXTRA
;
810 return realloc(p
, nbytes
);
821 /* These methods are used to control infinite recursion in repr, str, print,
822 etc. Container objects that may recursively contain themselves,
823 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
824 Py_ReprLeave() to avoid infinite recursion.
826 Py_ReprEnter() returns 0 the first time it is called for a particular
827 object and 1 every time thereafter. It returns -1 if an exception
828 occurred. Py_ReprLeave() has no return value.
830 See dictobject.c and listobject.c for examples of use.
833 #define KEY "Py_Repr"
843 dict
= PyThreadState_GetDict();
846 list
= PyDict_GetItemString(dict
, KEY
);
848 list
= PyList_New(0);
851 if (PyDict_SetItemString(dict
, KEY
, list
) < 0)
855 i
= PyList_GET_SIZE(list
);
857 if (PyList_GET_ITEM(list
, i
) == obj
)
860 PyList_Append(list
, obj
);
872 dict
= PyThreadState_GetDict();
875 list
= PyDict_GetItemString(dict
, KEY
);
876 if (list
== NULL
|| !PyList_Check(list
))
878 i
= PyList_GET_SIZE(list
);
879 /* Count backwards because we always expect obj to be list[-1] */
881 if (PyList_GET_ITEM(list
, i
) == obj
) {
882 PyList_SetSlice(list
, i
, i
+ 1, NULL
);