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 )
37 DL_IMPORT(long) _Py_RefTotal
;
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((PyObject
*)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");
171 clearerr(fp
); /* Clear any previous error condition */
173 fprintf(fp
, "<nil>");
176 if (op
->ob_refcnt
<= 0)
177 fprintf(fp
, "<refcnt %u at %lx>",
178 op
->ob_refcnt
, (long)op
);
179 else if (op
->ob_type
->tp_print
== NULL
) {
180 if (op
->ob_type
->tp_repr
== NULL
) {
181 fprintf(fp
, "<%s object at %lx>",
182 op
->ob_type
->tp_name
, (long)op
);
186 if (flags
& Py_PRINT_RAW
)
187 s
= PyObject_Str(op
);
189 s
= PyObject_Repr(op
);
192 else if (!PyString_Check(s
)) {
193 PyErr_SetString(PyExc_TypeError
,
198 ret
= PyObject_Print(s
, fp
,
205 ret
= (*op
->ob_type
->tp_print
)(op
, fp
, flags
);
209 PyErr_SetFromErrno(PyExc_IOError
);
221 if (PyErr_CheckSignals())
223 #ifdef USE_STACKCHECK
224 if (PyOS_CheckStack()) {
225 PyErr_SetString(PyExc_MemoryError
, "Stack overflow");
230 return PyString_FromString("<NULL>");
231 else if (v
->ob_type
->tp_repr
== NULL
) {
233 sprintf(buf
, "<%.80s object at %lx>",
234 v
->ob_type
->tp_name
, (long)v
);
235 return PyString_FromString(buf
);
238 return (*v
->ob_type
->tp_repr
)(v
);
246 return PyString_FromString("<NULL>");
247 else if (PyString_Check(v
)) {
251 else if (v
->ob_type
->tp_str
!= NULL
)
252 return (*v
->ob_type
->tp_str
)(v
);
256 if (!PyInstance_Check(v
) ||
257 (func
= PyObject_GetAttrString(v
, "__str__")) == NULL
) {
259 return PyObject_Repr(v
);
261 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
272 /* __rcmp__ actually won't be called unless __cmp__ isn't defined,
273 because the check in cmpobject() reverses the objects first.
274 This is intentional -- it makes no sense to define cmp(x,y)
275 different than -cmp(y,x). */
276 if (PyInstance_Check(v
) || PyInstance_Check(w
))
277 return PyInstance_DoBinOp(v
, w
, "__cmp__", "__rcmp__", do_cmp
);
278 c
= PyObject_Compare(v
, w
);
279 if (c
&& PyErr_Occurred())
281 return PyInt_FromLong(c
);
285 PyObject_Compare(v
, w
)
288 PyTypeObject
*vtp
, *wtp
;
289 if (v
== NULL
|| w
== NULL
) {
290 PyErr_BadInternalCall();
295 if (PyInstance_Check(v
) || PyInstance_Check(w
)) {
298 if (!PyInstance_Check(v
))
299 return -PyObject_Compare(w
, v
);
303 if (!PyInt_Check(res
)) {
305 PyErr_SetString(PyExc_TypeError
,
306 "comparison did not return an int");
309 c
= PyInt_AsLong(res
);
311 return (c
< 0) ? -1 : (c
> 0) ? 1 : 0;
313 if ((vtp
= v
->ob_type
) != (wtp
= w
->ob_type
)) {
314 char *vname
= vtp
->tp_name
;
315 char *wname
= wtp
->tp_name
;
316 if (vtp
->tp_as_number
!= NULL
&& wtp
->tp_as_number
!= NULL
) {
318 err
= PyNumber_CoerceEx(&v
, &w
);
324 if (vtp
->tp_compare
== NULL
)
325 cmp
= (v
< w
) ? -1 : 1;
327 cmp
= (*vtp
->tp_compare
)(v
, w
);
333 else if (vtp
->tp_as_number
!= NULL
)
335 else if (wtp
->tp_as_number
!= NULL
)
337 /* Numerical types compare smaller than all other types */
338 return strcmp(vname
, wname
);
340 if (vtp
->tp_compare
== NULL
)
341 return (v
< w
) ? -1 : 1;
342 return (*vtp
->tp_compare
)(v
, w
);
349 PyTypeObject
*tp
= v
->ob_type
;
350 if (tp
->tp_hash
!= NULL
)
351 return (*tp
->tp_hash
)(v
);
352 if (tp
->tp_compare
== NULL
)
353 return (long) v
; /* Use address as hash value */
354 /* If there's a cmp but no hash defined, the object can't be hashed */
355 PyErr_SetString(PyExc_TypeError
, "unhashable type");
360 PyObject_GetAttrString(v
, name
)
364 if (v
->ob_type
->tp_getattro
!= NULL
) {
366 w
= PyString_InternFromString(name
);
369 res
= (*v
->ob_type
->tp_getattro
)(v
, w
);
374 if (v
->ob_type
->tp_getattr
== NULL
) {
375 PyErr_Format(PyExc_AttributeError
,
376 "'%.50s' object has no attribute '%.400s'",
382 return (*v
->ob_type
->tp_getattr
)(v
, name
);
387 PyObject_HasAttrString(v
, name
)
391 PyObject
*res
= PyObject_GetAttrString(v
, name
);
401 PyObject_SetAttrString(v
, name
, w
)
406 if (v
->ob_type
->tp_setattro
!= NULL
) {
409 s
= PyString_InternFromString(name
);
412 res
= (*v
->ob_type
->tp_setattro
)(v
, s
, w
);
417 if (v
->ob_type
->tp_setattr
== NULL
) {
418 if (v
->ob_type
->tp_getattr
== NULL
)
419 PyErr_SetString(PyExc_TypeError
,
420 "attribute-less object (assign or del)");
422 PyErr_SetString(PyExc_TypeError
,
423 "object has read-only attributes");
427 return (*v
->ob_type
->tp_setattr
)(v
, name
, w
);
432 PyObject_GetAttr(v
, name
)
436 if (v
->ob_type
->tp_getattro
!= NULL
)
437 return (*v
->ob_type
->tp_getattro
)(v
, name
);
439 return PyObject_GetAttrString(v
, PyString_AsString(name
));
443 PyObject_HasAttr(v
, name
)
447 PyObject
*res
= PyObject_GetAttr(v
, name
);
457 PyObject_SetAttr(v
, name
, value
)
464 PyString_InternInPlace(&name
);
465 if (v
->ob_type
->tp_setattro
!= NULL
)
466 err
= (*v
->ob_type
->tp_setattro
)(v
, name
, value
);
468 err
= PyObject_SetAttrString(
469 v
, PyString_AsString(name
), value
);
474 /* Test a value used as condition, e.g., in a for or if statement.
475 Return -1 if an error occurred */
484 else if (v
->ob_type
->tp_as_number
!= NULL
&&
485 v
->ob_type
->tp_as_number
->nb_nonzero
!= NULL
)
486 res
= (*v
->ob_type
->tp_as_number
->nb_nonzero
)(v
);
487 else if (v
->ob_type
->tp_as_mapping
!= NULL
&&
488 v
->ob_type
->tp_as_mapping
->mp_length
!= NULL
)
489 res
= (*v
->ob_type
->tp_as_mapping
->mp_length
)(v
);
490 else if (v
->ob_type
->tp_as_sequence
!= NULL
&&
491 v
->ob_type
->tp_as_sequence
->sq_length
!= NULL
)
492 res
= (*v
->ob_type
->tp_as_sequence
->sq_length
)(v
);
500 /* equivalent of 'not v'
501 Return -1 if an error occurred */
508 res
= PyObject_IsTrue(v
);
514 /* Coerce two numeric types to the "larger" one.
515 Increment the reference count on each argument.
516 Return -1 and raise an exception if no coercion is possible
517 (and then no reference count is incremented).
521 PyNumber_CoerceEx(pv
, pw
)
524 register PyObject
*v
= *pv
;
525 register PyObject
*w
= *pw
;
528 if (v
->ob_type
== w
->ob_type
&& !PyInstance_Check(v
)) {
533 if (v
->ob_type
->tp_as_number
&& v
->ob_type
->tp_as_number
->nb_coerce
) {
534 res
= (*v
->ob_type
->tp_as_number
->nb_coerce
)(pv
, pw
);
538 if (w
->ob_type
->tp_as_number
&& w
->ob_type
->tp_as_number
->nb_coerce
) {
539 res
= (*w
->ob_type
->tp_as_number
->nb_coerce
)(pw
, pv
);
547 PyNumber_Coerce(pv
, pw
)
550 int err
= PyNumber_CoerceEx(pv
, pw
);
553 PyErr_SetString(PyExc_TypeError
, "number coercion failed");
558 /* Test whether an object can be called */
566 if (x
->ob_type
->tp_call
!= NULL
||
567 PyFunction_Check(x
) ||
569 PyCFunction_Check(x
) ||
572 if (PyInstance_Check(x
)) {
573 PyObject
*call
= PyObject_GetAttrString(x
, "__call__");
578 /* Could test recursively but don't, for fear of endless
579 recursion if some joker sets self.__call__ = self */
588 NoObject is usable as a non-NULL undefined value, used by the macro None.
589 There is (and should be!) no way to create other objects of this type,
590 so there is exactly one (which is indestructible, by the way).
598 return PyString_FromString("None");
601 static PyTypeObject PyNothing_Type
= {
602 PyObject_HEAD_INIT(&PyType_Type
)
607 0, /*tp_dealloc*/ /*never called*/
612 (reprfunc
)none_repr
, /*tp_repr*/
614 0, /*tp_as_sequence*/
619 PyObject _Py_NoneStruct
= {
620 PyObject_HEAD_INIT(&PyNothing_Type
)
626 static PyObject refchain
= {&refchain
, &refchain
};
629 _Py_ResetReferences()
631 refchain
._ob_prev
= refchain
._ob_next
= &refchain
;
641 op
->_ob_next
= refchain
._ob_next
;
642 op
->_ob_prev
= &refchain
;
643 refchain
._ob_next
->_ob_prev
= op
;
644 refchain
._ob_next
= op
;
646 inc_count(op
->ob_type
);
651 _Py_ForgetReference(op
)
652 register PyObject
*op
;
654 #ifdef SLOW_UNREF_CHECK
655 register PyObject
*p
;
657 if (op
->ob_refcnt
< 0)
658 Py_FatalError("UNREF negative refcnt");
659 if (op
== &refchain
||
660 op
->_ob_prev
->_ob_next
!= op
|| op
->_ob_next
->_ob_prev
!= op
)
661 Py_FatalError("UNREF invalid object");
662 #ifdef SLOW_UNREF_CHECK
663 for (p
= refchain
._ob_next
; p
!= &refchain
; p
= p
->_ob_next
) {
667 if (p
== &refchain
) /* Not found */
668 Py_FatalError("UNREF unknown object");
670 op
->_ob_next
->_ob_prev
= op
->_ob_prev
;
671 op
->_ob_prev
->_ob_next
= op
->_ob_next
;
672 op
->_ob_next
= op
->_ob_prev
= NULL
;
674 op
->ob_type
->tp_free
++;
682 destructor dealloc
= op
->ob_type
->tp_dealloc
;
683 _Py_ForgetReference(op
);
689 _Py_PrintReferences(fp
)
693 fprintf(fp
, "Remaining objects:\n");
694 for (op
= refchain
._ob_next
; op
!= &refchain
; op
= op
->_ob_next
) {
695 fprintf(fp
, "[%d] ", op
->ob_refcnt
);
696 if (PyObject_Print(op
, fp
, 0) != 0)
703 _Py_GetObjects(self
, args
)
711 if (!PyArg_ParseTuple(args
, "i|O", &n
, &t
))
713 op
= refchain
._ob_next
;
717 for (i
= 0; (n
== 0 || i
< n
) && op
!= &refchain
; i
++) {
718 while (op
== self
|| op
== args
|| op
== res
|| op
== t
||
719 t
!= NULL
&& op
->ob_type
!= (PyTypeObject
*) t
) {
724 if (PyList_Append(res
, op
) < 0) {
736 /* Hack to force loading of cobject.o */
737 PyTypeObject
*_Py_cobject_hack
= &PyCObject_Type
;
740 /* Hack to force loading of abstract.o */
741 int (*_Py_abstract_hack
) Py_FPROTO((PyObject
*)) = &PyObject_Length
;
744 /* Malloc wrappers (see mymalloc.h) */
746 /* The Py_{Malloc,Realloc} wrappers call PyErr_NoMemory() on failure */
755 nbytes
= _PyMem_EXTRA
;
767 Py_Realloc(p
, nbytes
)
773 nbytes
= _PyMem_EXTRA
;
775 p
= realloc(p
, nbytes
);
791 /* The PyMem_{Malloc,Realloc} wrappers don't call anything on failure */
799 nbytes
= _PyMem_EXTRA
;
801 return malloc(nbytes
);
805 PyMem_Realloc(p
, nbytes
)
811 nbytes
= _PyMem_EXTRA
;
813 return realloc(p
, nbytes
);
824 /* These methods are used to control infinite recursion in repr, str, print,
825 etc. Container objects that may recursively contain themselves,
826 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
827 Py_ReprLeave() to avoid infinite recursion.
829 Py_ReprEnter() returns 0 the first time it is called for a particular
830 object and 1 every time thereafter. It returns -1 if an exception
831 occurred. Py_ReprLeave() has no return value.
833 See dictobject.c and listobject.c for examples of use.
836 #define KEY "Py_Repr"
846 dict
= PyThreadState_GetDict();
849 list
= PyDict_GetItemString(dict
, KEY
);
851 list
= PyList_New(0);
854 if (PyDict_SetItemString(dict
, KEY
, list
) < 0)
858 i
= PyList_GET_SIZE(list
);
860 if (PyList_GET_ITEM(list
, i
) == obj
)
863 PyList_Append(list
, obj
);
875 dict
= PyThreadState_GetDict();
878 list
= PyDict_GetItemString(dict
, KEY
);
879 if (list
== NULL
|| !PyList_Check(list
))
881 i
= PyList_GET_SIZE(list
);
882 /* Count backwards because we always expect obj to be list[-1] */
884 if (PyList_GET_ITEM(list
, i
) == obj
) {
885 PyList_SetSlice(list
, i
, i
+ 1, NULL
);