Back to index

python3.2  3.2.2
object.h
Go to the documentation of this file.
00001 #ifndef Py_OBJECT_H
00002 #define Py_OBJECT_H
00003 #ifdef __cplusplus
00004 extern "C" {
00005 #endif
00006 
00007 
00008 /* Object and type object interface */
00009 
00010 /*
00011 Objects are structures allocated on the heap.  Special rules apply to
00012 the use of objects to ensure they are properly garbage-collected.
00013 Objects are never allocated statically or on the stack; they must be
00014 accessed through special macros and functions only.  (Type objects are
00015 exceptions to the first rule; the standard types are represented by
00016 statically initialized type objects, although work on type/class unification
00017 for Python 2.2 made it possible to have heap-allocated type objects too).
00018 
00019 An object has a 'reference count' that is increased or decreased when a
00020 pointer to the object is copied or deleted; when the reference count
00021 reaches zero there are no references to the object left and it can be
00022 removed from the heap.
00023 
00024 An object has a 'type' that determines what it represents and what kind
00025 of data it contains.  An object's type is fixed when it is created.
00026 Types themselves are represented as objects; an object contains a
00027 pointer to the corresponding type object.  The type itself has a type
00028 pointer pointing to the object representing the type 'type', which
00029 contains a pointer to itself!).
00030 
00031 Objects do not float around in memory; once allocated an object keeps
00032 the same size and address.  Objects that must hold variable-size data
00033 can contain pointers to variable-size parts of the object.  Not all
00034 objects of the same type have the same size; but the size cannot change
00035 after allocation.  (These restrictions are made so a reference to an
00036 object can be simply a pointer -- moving an object would require
00037 updating all the pointers, and changing an object's size would require
00038 moving it if there was another object right next to it.)
00039 
00040 Objects are always accessed through pointers of the type 'PyObject *'.
00041 The type 'PyObject' is a structure that only contains the reference count
00042 and the type pointer.  The actual memory allocated for an object
00043 contains other data that can only be accessed after casting the pointer
00044 to a pointer to a longer structure type.  This longer type must start
00045 with the reference count and type fields; the macro PyObject_HEAD should be
00046 used for this (to accommodate for future changes).  The implementation
00047 of a particular object type can cast the object pointer to the proper
00048 type and back.
00049 
00050 A standard interface exists for objects that contain an array of items
00051 whose size is determined when the object is allocated.
00052 */
00053 
00054 /* Py_DEBUG implies Py_TRACE_REFS. */
00055 #if defined(Py_DEBUG) && !defined(Py_TRACE_REFS)
00056 #define Py_TRACE_REFS
00057 #endif
00058 
00059 /* Py_TRACE_REFS implies Py_REF_DEBUG. */
00060 #if defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG)
00061 #define Py_REF_DEBUG
00062 #endif
00063 
00064 #if defined(Py_LIMITED_API) && defined(Py_REF_DEBUG)
00065 #error Py_LIMITED_API is incompatible with Py_DEBUG, Py_TRACE_REFS, and Py_REF_DEBUG
00066 #endif
00067 
00068 #ifdef Py_TRACE_REFS
00069 /* Define pointers to support a doubly-linked list of all live heap objects. */
00070 #define _PyObject_HEAD_EXTRA            \
00071     struct _object *_ob_next;           \
00072     struct _object *_ob_prev;
00073 
00074 #define _PyObject_EXTRA_INIT 0, 0,
00075 
00076 #else
00077 #define _PyObject_HEAD_EXTRA
00078 #define _PyObject_EXTRA_INIT
00079 #endif
00080 
00081 /* PyObject_HEAD defines the initial segment of every PyObject. */
00082 #define PyObject_HEAD                   PyObject ob_base;
00083 
00084 #define PyObject_HEAD_INIT(type)        \
00085     { _PyObject_EXTRA_INIT              \
00086     1, type },
00087 
00088 #define PyVarObject_HEAD_INIT(type, size)       \
00089     { PyObject_HEAD_INIT(type) size },
00090 
00091 /* PyObject_VAR_HEAD defines the initial segment of all variable-size
00092  * container objects.  These end with a declaration of an array with 1
00093  * element, but enough space is malloc'ed so that the array actually
00094  * has room for ob_size elements.  Note that ob_size is an element count,
00095  * not necessarily a byte count.
00096  */
00097 #define PyObject_VAR_HEAD      PyVarObject ob_base;
00098 #define Py_INVALID_SIZE (Py_ssize_t)-1
00099 
00100 /* Nothing is actually declared to be a PyObject, but every pointer to
00101  * a Python object can be cast to a PyObject*.  This is inheritance built
00102  * by hand.  Similarly every pointer to a variable-size Python object can,
00103  * in addition, be cast to PyVarObject*.
00104  */
00105 typedef struct _object {
00106     _PyObject_HEAD_EXTRA
00107     Py_ssize_t ob_refcnt;
00108     struct _typeobject *ob_type;
00109 } PyObject;
00110 
00111 typedef struct {
00112     PyObject ob_base;
00113     Py_ssize_t ob_size; /* Number of items in variable part */
00114 } PyVarObject;
00115 
00116 #define Py_REFCNT(ob)           (((PyObject*)(ob))->ob_refcnt)
00117 #define Py_TYPE(ob)             (((PyObject*)(ob))->ob_type)
00118 #define Py_SIZE(ob)             (((PyVarObject*)(ob))->ob_size)
00119 
00120 /*
00121 Type objects contain a string containing the type name (to help somewhat
00122 in debugging), the allocation parameters (see PyObject_New() and
00123 PyObject_NewVar()),
00124 and methods for accessing objects of the type.  Methods are optional, a
00125 nil pointer meaning that particular kind of access is not available for
00126 this type.  The Py_DECREF() macro uses the tp_dealloc method without
00127 checking for a nil pointer; it should always be implemented except if
00128 the implementation can guarantee that the reference count will never
00129 reach zero (e.g., for statically allocated type objects).
00130 
00131 NB: the methods for certain type groups are now contained in separate
00132 method blocks.
00133 */
00134 
00135 typedef PyObject * (*unaryfunc)(PyObject *);
00136 typedef PyObject * (*binaryfunc)(PyObject *, PyObject *);
00137 typedef PyObject * (*ternaryfunc)(PyObject *, PyObject *, PyObject *);
00138 typedef int (*inquiry)(PyObject *);
00139 typedef Py_ssize_t (*lenfunc)(PyObject *);
00140 typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t);
00141 typedef PyObject *(*ssizessizeargfunc)(PyObject *, Py_ssize_t, Py_ssize_t);
00142 typedef int(*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *);
00143 typedef int(*ssizessizeobjargproc)(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
00144 typedef int(*objobjargproc)(PyObject *, PyObject *, PyObject *);
00145 
00146 #ifndef Py_LIMITED_API
00147 /* buffer interface */
00148 typedef struct bufferinfo {
00149     void *buf;
00150     PyObject *obj;        /* owned reference */
00151     Py_ssize_t len;
00152     Py_ssize_t itemsize;  /* This is Py_ssize_t so it can be
00153                              pointed to by strides in simple case.*/
00154     int readonly;
00155     int ndim;
00156     char *format;
00157     Py_ssize_t *shape;
00158     Py_ssize_t *strides;
00159     Py_ssize_t *suboffsets;
00160     Py_ssize_t smalltable[2];  /* static store for shape and strides of
00161                                   mono-dimensional buffers. */
00162     void *internal;
00163 } Py_buffer;
00164 
00165 typedef int (*getbufferproc)(PyObject *, Py_buffer *, int);
00166 typedef void (*releasebufferproc)(PyObject *, Py_buffer *);
00167 
00168     /* Flags for getting buffers */
00169 #define PyBUF_SIMPLE 0
00170 #define PyBUF_WRITABLE 0x0001
00171 /*  we used to include an E, backwards compatible alias  */
00172 #define PyBUF_WRITEABLE PyBUF_WRITABLE
00173 #define PyBUF_FORMAT 0x0004
00174 #define PyBUF_ND 0x0008
00175 #define PyBUF_STRIDES (0x0010 | PyBUF_ND)
00176 #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES)
00177 #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES)
00178 #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES)
00179 #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES)
00180 
00181 #define PyBUF_CONTIG (PyBUF_ND | PyBUF_WRITABLE)
00182 #define PyBUF_CONTIG_RO (PyBUF_ND)
00183 
00184 #define PyBUF_STRIDED (PyBUF_STRIDES | PyBUF_WRITABLE)
00185 #define PyBUF_STRIDED_RO (PyBUF_STRIDES)
00186 
00187 #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_WRITABLE | PyBUF_FORMAT)
00188 #define PyBUF_RECORDS_RO (PyBUF_STRIDES | PyBUF_FORMAT)
00189 
00190 #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_WRITABLE | PyBUF_FORMAT)
00191 #define PyBUF_FULL_RO (PyBUF_INDIRECT | PyBUF_FORMAT)
00192 
00193 
00194 #define PyBUF_READ  0x100
00195 #define PyBUF_WRITE 0x200
00196 
00197 /* End buffer interface */
00198 #endif /* Py_LIMITED_API */
00199 
00200 typedef int (*objobjproc)(PyObject *, PyObject *);
00201 typedef int (*visitproc)(PyObject *, void *);
00202 typedef int (*traverseproc)(PyObject *, visitproc, void *);
00203 
00204 #ifndef Py_LIMITED_API
00205 typedef struct {
00206     /* Number implementations must check *both*
00207        arguments for proper type and implement the necessary conversions
00208        in the slot functions themselves. */
00209 
00210     binaryfunc nb_add;
00211     binaryfunc nb_subtract;
00212     binaryfunc nb_multiply;
00213     binaryfunc nb_remainder;
00214     binaryfunc nb_divmod;
00215     ternaryfunc nb_power;
00216     unaryfunc nb_negative;
00217     unaryfunc nb_positive;
00218     unaryfunc nb_absolute;
00219     inquiry nb_bool;
00220     unaryfunc nb_invert;
00221     binaryfunc nb_lshift;
00222     binaryfunc nb_rshift;
00223     binaryfunc nb_and;
00224     binaryfunc nb_xor;
00225     binaryfunc nb_or;
00226     unaryfunc nb_int;
00227     void *nb_reserved;  /* the slot formerly known as nb_long */
00228     unaryfunc nb_float;
00229 
00230     binaryfunc nb_inplace_add;
00231     binaryfunc nb_inplace_subtract;
00232     binaryfunc nb_inplace_multiply;
00233     binaryfunc nb_inplace_remainder;
00234     ternaryfunc nb_inplace_power;
00235     binaryfunc nb_inplace_lshift;
00236     binaryfunc nb_inplace_rshift;
00237     binaryfunc nb_inplace_and;
00238     binaryfunc nb_inplace_xor;
00239     binaryfunc nb_inplace_or;
00240 
00241     binaryfunc nb_floor_divide;
00242     binaryfunc nb_true_divide;
00243     binaryfunc nb_inplace_floor_divide;
00244     binaryfunc nb_inplace_true_divide;
00245 
00246     unaryfunc nb_index;
00247 } PyNumberMethods;
00248 
00249 typedef struct {
00250     lenfunc sq_length;
00251     binaryfunc sq_concat;
00252     ssizeargfunc sq_repeat;
00253     ssizeargfunc sq_item;
00254     void *was_sq_slice;
00255     ssizeobjargproc sq_ass_item;
00256     void *was_sq_ass_slice;
00257     objobjproc sq_contains;
00258 
00259     binaryfunc sq_inplace_concat;
00260     ssizeargfunc sq_inplace_repeat;
00261 } PySequenceMethods;
00262 
00263 typedef struct {
00264     lenfunc mp_length;
00265     binaryfunc mp_subscript;
00266     objobjargproc mp_ass_subscript;
00267 } PyMappingMethods;
00268 
00269 
00270 typedef struct {
00271      getbufferproc bf_getbuffer;
00272      releasebufferproc bf_releasebuffer;
00273 } PyBufferProcs;
00274 #endif /* Py_LIMITED_API */
00275 
00276 typedef void (*freefunc)(void *);
00277 typedef void (*destructor)(PyObject *);
00278 #ifndef Py_LIMITED_API
00279 /* We can't provide a full compile-time check that limited-API
00280    users won't implement tp_print. However, not defining printfunc
00281    and making tp_print of a different function pointer type
00282    should at least cause a warning in most cases. */
00283 typedef int (*printfunc)(PyObject *, FILE *, int);
00284 #endif
00285 typedef PyObject *(*getattrfunc)(PyObject *, char *);
00286 typedef PyObject *(*getattrofunc)(PyObject *, PyObject *);
00287 typedef int (*setattrfunc)(PyObject *, char *, PyObject *);
00288 typedef int (*setattrofunc)(PyObject *, PyObject *, PyObject *);
00289 typedef PyObject *(*reprfunc)(PyObject *);
00290 typedef Py_hash_t (*hashfunc)(PyObject *);
00291 typedef PyObject *(*richcmpfunc) (PyObject *, PyObject *, int);
00292 typedef PyObject *(*getiterfunc) (PyObject *);
00293 typedef PyObject *(*iternextfunc) (PyObject *);
00294 typedef PyObject *(*descrgetfunc) (PyObject *, PyObject *, PyObject *);
00295 typedef int (*descrsetfunc) (PyObject *, PyObject *, PyObject *);
00296 typedef int (*initproc)(PyObject *, PyObject *, PyObject *);
00297 typedef PyObject *(*newfunc)(struct _typeobject *, PyObject *, PyObject *);
00298 typedef PyObject *(*allocfunc)(struct _typeobject *, Py_ssize_t);
00299 
00300 #ifdef Py_LIMITED_API
00301 typedef struct _typeobject PyTypeObject; /* opaque */
00302 #else
00303 typedef struct _typeobject {
00304     PyObject_VAR_HEAD
00305     const char *tp_name; /* For printing, in format "<module>.<name>" */
00306     Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
00307 
00308     /* Methods to implement standard operations */
00309 
00310     destructor tp_dealloc;
00311     printfunc tp_print;
00312     getattrfunc tp_getattr;
00313     setattrfunc tp_setattr;
00314     void *tp_reserved; /* formerly known as tp_compare */
00315     reprfunc tp_repr;
00316 
00317     /* Method suites for standard classes */
00318 
00319     PyNumberMethods *tp_as_number;
00320     PySequenceMethods *tp_as_sequence;
00321     PyMappingMethods *tp_as_mapping;
00322 
00323     /* More standard operations (here for binary compatibility) */
00324 
00325     hashfunc tp_hash;
00326     ternaryfunc tp_call;
00327     reprfunc tp_str;
00328     getattrofunc tp_getattro;
00329     setattrofunc tp_setattro;
00330 
00331     /* Functions to access object as input/output buffer */
00332     PyBufferProcs *tp_as_buffer;
00333 
00334     /* Flags to define presence of optional/expanded features */
00335     long tp_flags;
00336 
00337     const char *tp_doc; /* Documentation string */
00338 
00339     /* Assigned meaning in release 2.0 */
00340     /* call function for all accessible objects */
00341     traverseproc tp_traverse;
00342 
00343     /* delete references to contained objects */
00344     inquiry tp_clear;
00345 
00346     /* Assigned meaning in release 2.1 */
00347     /* rich comparisons */
00348     richcmpfunc tp_richcompare;
00349 
00350     /* weak reference enabler */
00351     Py_ssize_t tp_weaklistoffset;
00352 
00353     /* Iterators */
00354     getiterfunc tp_iter;
00355     iternextfunc tp_iternext;
00356 
00357     /* Attribute descriptor and subclassing stuff */
00358     struct PyMethodDef *tp_methods;
00359     struct PyMemberDef *tp_members;
00360     struct PyGetSetDef *tp_getset;
00361     struct _typeobject *tp_base;
00362     PyObject *tp_dict;
00363     descrgetfunc tp_descr_get;
00364     descrsetfunc tp_descr_set;
00365     Py_ssize_t tp_dictoffset;
00366     initproc tp_init;
00367     allocfunc tp_alloc;
00368     newfunc tp_new;
00369     freefunc tp_free; /* Low-level free-memory routine */
00370     inquiry tp_is_gc; /* For PyObject_IS_GC */
00371     PyObject *tp_bases;
00372     PyObject *tp_mro; /* method resolution order */
00373     PyObject *tp_cache;
00374     PyObject *tp_subclasses;
00375     PyObject *tp_weaklist;
00376     destructor tp_del;
00377 
00378     /* Type attribute cache version tag. Added in version 2.6 */
00379     unsigned int tp_version_tag;
00380 
00381 #ifdef COUNT_ALLOCS
00382     /* these must be last and never explicitly initialized */
00383     Py_ssize_t tp_allocs;
00384     Py_ssize_t tp_frees;
00385     Py_ssize_t tp_maxalloc;
00386     struct _typeobject *tp_prev;
00387     struct _typeobject *tp_next;
00388 #endif
00389 } PyTypeObject;
00390 #endif
00391 
00392 typedef struct{
00393     int slot;    /* slot id, see below */
00394     void *pfunc; /* function pointer */
00395 } PyType_Slot;
00396 
00397 typedef struct{
00398     const char* name;
00399     int basicsize;
00400     int itemsize;
00401     int flags;
00402     PyType_Slot *slots; /* terminated by slot==0. */
00403 } PyType_Spec;
00404 
00405 PyAPI_FUNC(PyObject*) PyType_FromSpec(PyType_Spec*);
00406 
00407 #ifndef Py_LIMITED_API
00408 /* The *real* layout of a type object when allocated on the heap */
00409 typedef struct _heaptypeobject {
00410     /* Note: there's a dependency on the order of these members
00411        in slotptr() in typeobject.c . */
00412     PyTypeObject ht_type;
00413     PyNumberMethods as_number;
00414     PyMappingMethods as_mapping;
00415     PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
00416                                       so that the mapping wins when both
00417                                       the mapping and the sequence define
00418                                       a given operator (e.g. __getitem__).
00419                                       see add_operators() in typeobject.c . */
00420     PyBufferProcs as_buffer;
00421     PyObject *ht_name, *ht_slots;
00422     /* here are optional user slots, followed by the members. */
00423 } PyHeapTypeObject;
00424 
00425 /* access macro to the members which are floating "behind" the object */
00426 #define PyHeapType_GET_MEMBERS(etype) \
00427     ((PyMemberDef *)(((char *)etype) + Py_TYPE(etype)->tp_basicsize))
00428 #endif
00429 
00430 /* Generic type check */
00431 PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *);
00432 #define PyObject_TypeCheck(ob, tp) \
00433     (Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp)))
00434 
00435 PyAPI_DATA(PyTypeObject) PyType_Type; /* built-in 'type' */
00436 PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */
00437 PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */
00438 
00439 PyAPI_FUNC(long) PyType_GetFlags(PyTypeObject*);
00440 
00441 #define PyType_Check(op) \
00442     PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS)
00443 #define PyType_CheckExact(op) (Py_TYPE(op) == &PyType_Type)
00444 
00445 PyAPI_FUNC(int) PyType_Ready(PyTypeObject *);
00446 PyAPI_FUNC(PyObject *) PyType_GenericAlloc(PyTypeObject *, Py_ssize_t);
00447 PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *,
00448                                                PyObject *, PyObject *);
00449 #ifndef Py_LIMITED_API
00450 PyAPI_FUNC(PyObject *) _PyType_Lookup(PyTypeObject *, PyObject *);
00451 PyAPI_FUNC(PyObject *) _PyObject_LookupSpecial(PyObject *, char *, PyObject **);
00452 #endif
00453 PyAPI_FUNC(unsigned int) PyType_ClearCache(void);
00454 PyAPI_FUNC(void) PyType_Modified(PyTypeObject *);
00455 
00456 /* Generic operations on objects */
00457 #ifndef Py_LIMITED_API
00458 PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int);
00459 PyAPI_FUNC(void) _Py_BreakPoint(void);
00460 PyAPI_FUNC(void) _PyObject_Dump(PyObject *);
00461 #endif
00462 PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *);
00463 PyAPI_FUNC(PyObject *) PyObject_Str(PyObject *);
00464 PyAPI_FUNC(PyObject *) PyObject_ASCII(PyObject *);
00465 PyAPI_FUNC(PyObject *) PyObject_Bytes(PyObject *);
00466 PyAPI_FUNC(PyObject *) PyObject_RichCompare(PyObject *, PyObject *, int);
00467 PyAPI_FUNC(int) PyObject_RichCompareBool(PyObject *, PyObject *, int);
00468 PyAPI_FUNC(PyObject *) PyObject_GetAttrString(PyObject *, const char *);
00469 PyAPI_FUNC(int) PyObject_SetAttrString(PyObject *, const char *, PyObject *);
00470 PyAPI_FUNC(int) PyObject_HasAttrString(PyObject *, const char *);
00471 PyAPI_FUNC(PyObject *) PyObject_GetAttr(PyObject *, PyObject *);
00472 PyAPI_FUNC(int) PyObject_SetAttr(PyObject *, PyObject *, PyObject *);
00473 PyAPI_FUNC(int) PyObject_HasAttr(PyObject *, PyObject *);
00474 #ifndef Py_LIMITED_API
00475 PyAPI_FUNC(PyObject **) _PyObject_GetDictPtr(PyObject *);
00476 #endif
00477 PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *);
00478 #ifndef Py_LIMITED_API
00479 PyAPI_FUNC(PyObject *) _PyObject_NextNotImplemented(PyObject *);
00480 #endif
00481 PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);
00482 PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *,
00483                                               PyObject *, PyObject *);
00484 PyAPI_FUNC(Py_hash_t) PyObject_Hash(PyObject *);
00485 PyAPI_FUNC(Py_hash_t) PyObject_HashNotImplemented(PyObject *);
00486 PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);
00487 PyAPI_FUNC(int) PyObject_Not(PyObject *);
00488 PyAPI_FUNC(int) PyCallable_Check(PyObject *);
00489 
00490 PyAPI_FUNC(void) PyObject_ClearWeakRefs(PyObject *);
00491 
00492 /* Same as PyObject_Generic{Get,Set}Attr, but passing the attributes
00493    dict as the last parameter. */
00494 PyAPI_FUNC(PyObject *)
00495 _PyObject_GenericGetAttrWithDict(PyObject *, PyObject *, PyObject *);
00496 PyAPI_FUNC(int)
00497 _PyObject_GenericSetAttrWithDict(PyObject *, PyObject *,
00498                                  PyObject *, PyObject *);
00499 
00500 
00501 /* PyObject_Dir(obj) acts like Python builtins.dir(obj), returning a
00502    list of strings.  PyObject_Dir(NULL) is like builtins.dir(),
00503    returning the names of the current locals.  In this case, if there are
00504    no current locals, NULL is returned, and PyErr_Occurred() is false.
00505 */
00506 PyAPI_FUNC(PyObject *) PyObject_Dir(PyObject *);
00507 
00508 
00509 /* Helpers for printing recursive container types */
00510 PyAPI_FUNC(int) Py_ReprEnter(PyObject *);
00511 PyAPI_FUNC(void) Py_ReprLeave(PyObject *);
00512 
00513 /* Helpers for hash functions */
00514 #ifndef Py_LIMITED_API
00515 PyAPI_FUNC(Py_hash_t) _Py_HashDouble(double);
00516 PyAPI_FUNC(Py_hash_t) _Py_HashPointer(void*);
00517 #endif
00518 
00519 /* Helper for passing objects to printf and the like */
00520 #define PyObject_REPR(obj) _PyUnicode_AsString(PyObject_Repr(obj))
00521 
00522 /* Flag bits for printing: */
00523 #define Py_PRINT_RAW    1       /* No string quotes etc. */
00524 
00525 /*
00526 `Type flags (tp_flags)
00527 
00528 These flags are used to extend the type structure in a backwards-compatible
00529 fashion. Extensions can use the flags to indicate (and test) when a given
00530 type structure contains a new feature. The Python core will use these when
00531 introducing new functionality between major revisions (to avoid mid-version
00532 changes in the PYTHON_API_VERSION).
00533 
00534 Arbitration of the flag bit positions will need to be coordinated among
00535 all extension writers who publically release their extensions (this will
00536 be fewer than you might expect!)..
00537 
00538 Most flags were removed as of Python 3.0 to make room for new flags.  (Some
00539 flags are not for backwards compatibility but to indicate the presence of an
00540 optional feature; these flags remain of course.)
00541 
00542 Type definitions should use Py_TPFLAGS_DEFAULT for their tp_flags value.
00543 
00544 Code can use PyType_HasFeature(type_ob, flag_value) to test whether the
00545 given type object has a specified feature.
00546 */
00547 
00548 /* Set if the type object is dynamically allocated */
00549 #define Py_TPFLAGS_HEAPTYPE (1L<<9)
00550 
00551 /* Set if the type allows subclassing */
00552 #define Py_TPFLAGS_BASETYPE (1L<<10)
00553 
00554 /* Set if the type is 'ready' -- fully initialized */
00555 #define Py_TPFLAGS_READY (1L<<12)
00556 
00557 /* Set while the type is being 'readied', to prevent recursive ready calls */
00558 #define Py_TPFLAGS_READYING (1L<<13)
00559 
00560 /* Objects support garbage collection (see objimp.h) */
00561 #define Py_TPFLAGS_HAVE_GC (1L<<14)
00562 
00563 /* These two bits are preserved for Stackless Python, next after this is 17 */
00564 #ifdef STACKLESS
00565 #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION (3L<<15)
00566 #else
00567 #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0
00568 #endif
00569 
00570 /* Objects support type attribute cache */
00571 #define Py_TPFLAGS_HAVE_VERSION_TAG   (1L<<18)
00572 #define Py_TPFLAGS_VALID_VERSION_TAG  (1L<<19)
00573 
00574 /* Type is abstract and cannot be instantiated */
00575 #define Py_TPFLAGS_IS_ABSTRACT (1L<<20)
00576 
00577 /* These flags are used to determine if a type is a subclass. */
00578 #define Py_TPFLAGS_INT_SUBCLASS         (1L<<23)
00579 #define Py_TPFLAGS_LONG_SUBCLASS        (1L<<24)
00580 #define Py_TPFLAGS_LIST_SUBCLASS        (1L<<25)
00581 #define Py_TPFLAGS_TUPLE_SUBCLASS       (1L<<26)
00582 #define Py_TPFLAGS_BYTES_SUBCLASS       (1L<<27)
00583 #define Py_TPFLAGS_UNICODE_SUBCLASS     (1L<<28)
00584 #define Py_TPFLAGS_DICT_SUBCLASS        (1L<<29)
00585 #define Py_TPFLAGS_BASE_EXC_SUBCLASS    (1L<<30)
00586 #define Py_TPFLAGS_TYPE_SUBCLASS        (1L<<31)
00587 
00588 #define Py_TPFLAGS_DEFAULT  ( \
00589                  Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \
00590                  Py_TPFLAGS_HAVE_VERSION_TAG | \
00591                 0)
00592 
00593 #ifdef Py_LIMITED_API
00594 #define PyType_HasFeature(t,f)  ((PyType_GetFlags(t) & (f)) != 0)
00595 #else
00596 #define PyType_HasFeature(t,f)  (((t)->tp_flags & (f)) != 0)
00597 #endif
00598 #define PyType_FastSubclass(t,f)  PyType_HasFeature(t,f)
00599 
00600 
00601 /*
00602 The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement
00603 reference counts.  Py_DECREF calls the object's deallocator function when
00604 the refcount falls to 0; for
00605 objects that don't contain references to other objects or heap memory
00606 this can be the standard function free().  Both macros can be used
00607 wherever a void expression is allowed.  The argument must not be a
00608 NULL pointer.  If it may be NULL, use Py_XINCREF/Py_XDECREF instead.
00609 The macro _Py_NewReference(op) initialize reference counts to 1, and
00610 in special builds (Py_REF_DEBUG, Py_TRACE_REFS) performs additional
00611 bookkeeping appropriate to the special build.
00612 
00613 We assume that the reference count field can never overflow; this can
00614 be proven when the size of the field is the same as the pointer size, so
00615 we ignore the possibility.  Provided a C int is at least 32 bits (which
00616 is implicitly assumed in many parts of this code), that's enough for
00617 about 2**31 references to an object.
00618 
00619 XXX The following became out of date in Python 2.2, but I'm not sure
00620 XXX what the full truth is now.  Certainly, heap-allocated type objects
00621 XXX can and should be deallocated.
00622 Type objects should never be deallocated; the type pointer in an object
00623 is not considered to be a reference to the type object, to save
00624 complications in the deallocation function.  (This is actually a
00625 decision that's up to the implementer of each new type so if you want,
00626 you can count such references to the type object.)
00627 
00628 *** WARNING*** The Py_DECREF macro must have a side-effect-free argument
00629 since it may evaluate its argument multiple times.  (The alternative
00630 would be to mace it a proper function or assign it to a global temporary
00631 variable first, both of which are slower; and in a multi-threaded
00632 environment the global variable trick is not safe.)
00633 */
00634 
00635 /* First define a pile of simple helper macros, one set per special
00636  * build symbol.  These either expand to the obvious things, or to
00637  * nothing at all when the special mode isn't in effect.  The main
00638  * macros can later be defined just once then, yet expand to different
00639  * things depending on which special build options are and aren't in effect.
00640  * Trust me <wink>:  while painful, this is 20x easier to understand than,
00641  * e.g, defining _Py_NewReference five different times in a maze of nested
00642  * #ifdefs (we used to do that -- it was impenetrable).
00643  */
00644 #ifdef Py_REF_DEBUG
00645 PyAPI_DATA(Py_ssize_t) _Py_RefTotal;
00646 PyAPI_FUNC(void) _Py_NegativeRefcount(const char *fname,
00647                                             int lineno, PyObject *op);
00648 PyAPI_FUNC(PyObject *) _PyDict_Dummy(void);
00649 PyAPI_FUNC(PyObject *) _PySet_Dummy(void);
00650 PyAPI_FUNC(Py_ssize_t) _Py_GetRefTotal(void);
00651 #define _Py_INC_REFTOTAL        _Py_RefTotal++
00652 #define _Py_DEC_REFTOTAL        _Py_RefTotal--
00653 #define _Py_REF_DEBUG_COMMA     ,
00654 #define _Py_CHECK_REFCNT(OP)                                    \
00655 {       if (((PyObject*)OP)->ob_refcnt < 0)                             \
00656                 _Py_NegativeRefcount(__FILE__, __LINE__,        \
00657                                      (PyObject *)(OP));         \
00658 }
00659 #else
00660 #define _Py_INC_REFTOTAL
00661 #define _Py_DEC_REFTOTAL
00662 #define _Py_REF_DEBUG_COMMA
00663 #define _Py_CHECK_REFCNT(OP)    /* a semicolon */;
00664 #endif /* Py_REF_DEBUG */
00665 
00666 #ifdef COUNT_ALLOCS
00667 PyAPI_FUNC(void) inc_count(PyTypeObject *);
00668 PyAPI_FUNC(void) dec_count(PyTypeObject *);
00669 #define _Py_INC_TPALLOCS(OP)    inc_count(Py_TYPE(OP))
00670 #define _Py_INC_TPFREES(OP)     dec_count(Py_TYPE(OP))
00671 #define _Py_DEC_TPFREES(OP)     Py_TYPE(OP)->tp_frees--
00672 #define _Py_COUNT_ALLOCS_COMMA  ,
00673 #else
00674 #define _Py_INC_TPALLOCS(OP)
00675 #define _Py_INC_TPFREES(OP)
00676 #define _Py_DEC_TPFREES(OP)
00677 #define _Py_COUNT_ALLOCS_COMMA
00678 #endif /* COUNT_ALLOCS */
00679 
00680 #ifdef Py_TRACE_REFS
00681 /* Py_TRACE_REFS is such major surgery that we call external routines. */
00682 PyAPI_FUNC(void) _Py_NewReference(PyObject *);
00683 PyAPI_FUNC(void) _Py_ForgetReference(PyObject *);
00684 PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
00685 PyAPI_FUNC(void) _Py_PrintReferences(FILE *);
00686 PyAPI_FUNC(void) _Py_PrintReferenceAddresses(FILE *);
00687 PyAPI_FUNC(void) _Py_AddToAllObjects(PyObject *, int force);
00688 
00689 #else
00690 /* Without Py_TRACE_REFS, there's little enough to do that we expand code
00691  * inline.
00692  */
00693 #define _Py_NewReference(op) (                          \
00694     _Py_INC_TPALLOCS(op) _Py_COUNT_ALLOCS_COMMA         \
00695     _Py_INC_REFTOTAL  _Py_REF_DEBUG_COMMA               \
00696     Py_REFCNT(op) = 1)
00697 
00698 #define _Py_ForgetReference(op) _Py_INC_TPFREES(op)
00699 
00700 #ifdef Py_LIMITED_API
00701 PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
00702 #else
00703 #define _Py_Dealloc(op) (                               \
00704     _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA          \
00705     (*Py_TYPE(op)->tp_dealloc)((PyObject *)(op)))
00706 #endif
00707 #endif /* !Py_TRACE_REFS */
00708 
00709 #define Py_INCREF(op) (                         \
00710     _Py_INC_REFTOTAL  _Py_REF_DEBUG_COMMA       \
00711     ((PyObject*)(op))->ob_refcnt++)
00712 
00713 #define Py_DECREF(op)                                   \
00714     do {                                                \
00715         if (_Py_DEC_REFTOTAL  _Py_REF_DEBUG_COMMA       \
00716         --((PyObject*)(op))->ob_refcnt != 0)            \
00717             _Py_CHECK_REFCNT(op)                        \
00718         else                                            \
00719         _Py_Dealloc((PyObject *)(op));                  \
00720     } while (0)
00721 
00722 /* Safely decref `op` and set `op` to NULL, especially useful in tp_clear
00723  * and tp_dealloc implementatons.
00724  *
00725  * Note that "the obvious" code can be deadly:
00726  *
00727  *     Py_XDECREF(op);
00728  *     op = NULL;
00729  *
00730  * Typically, `op` is something like self->containee, and `self` is done
00731  * using its `containee` member.  In the code sequence above, suppose
00732  * `containee` is non-NULL with a refcount of 1.  Its refcount falls to
00733  * 0 on the first line, which can trigger an arbitrary amount of code,
00734  * possibly including finalizers (like __del__ methods or weakref callbacks)
00735  * coded in Python, which in turn can release the GIL and allow other threads
00736  * to run, etc.  Such code may even invoke methods of `self` again, or cause
00737  * cyclic gc to trigger, but-- oops! --self->containee still points to the
00738  * object being torn down, and it may be in an insane state while being torn
00739  * down.  This has in fact been a rich historic source of miserable (rare &
00740  * hard-to-diagnose) segfaulting (and other) bugs.
00741  *
00742  * The safe way is:
00743  *
00744  *      Py_CLEAR(op);
00745  *
00746  * That arranges to set `op` to NULL _before_ decref'ing, so that any code
00747  * triggered as a side-effect of `op` getting torn down no longer believes
00748  * `op` points to a valid object.
00749  *
00750  * There are cases where it's safe to use the naive code, but they're brittle.
00751  * For example, if `op` points to a Python integer, you know that destroying
00752  * one of those can't cause problems -- but in part that relies on that
00753  * Python integers aren't currently weakly referencable.  Best practice is
00754  * to use Py_CLEAR() even if you can't think of a reason for why you need to.
00755  */
00756 #define Py_CLEAR(op)                            \
00757     do {                                        \
00758         if (op) {                               \
00759             PyObject *_py_tmp = (PyObject *)(op);               \
00760             (op) = NULL;                        \
00761             Py_DECREF(_py_tmp);                 \
00762         }                                       \
00763     } while (0)
00764 
00765 /* Macros to use in case the object pointer may be NULL: */
00766 #define Py_XINCREF(op) do { if ((op) == NULL) ; else Py_INCREF(op); } while (0)
00767 #define Py_XDECREF(op) do { if ((op) == NULL) ; else Py_DECREF(op); } while (0)
00768 
00769 /*
00770 These are provided as conveniences to Python runtime embedders, so that
00771 they can have object code that is not dependent on Python compilation flags.
00772 */
00773 PyAPI_FUNC(void) Py_IncRef(PyObject *);
00774 PyAPI_FUNC(void) Py_DecRef(PyObject *);
00775 
00776 /*
00777 _Py_NoneStruct is an object of undefined type which can be used in contexts
00778 where NULL (nil) is not suitable (since NULL often means 'error').
00779 
00780 Don't forget to apply Py_INCREF() when returning this value!!!
00781 */
00782 PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */
00783 #define Py_None (&_Py_NoneStruct)
00784 
00785 /* Macro for returning Py_None from a function */
00786 #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
00787 
00788 /*
00789 Py_NotImplemented is a singleton used to signal that an operation is
00790 not implemented for a given type combination.
00791 */
00792 PyAPI_DATA(PyObject) _Py_NotImplementedStruct; /* Don't use this directly */
00793 #define Py_NotImplemented (&_Py_NotImplementedStruct)
00794 
00795 /* Rich comparison opcodes */
00796 #define Py_LT 0
00797 #define Py_LE 1
00798 #define Py_EQ 2
00799 #define Py_NE 3
00800 #define Py_GT 4
00801 #define Py_GE 5
00802 
00803 /* Maps Py_LT to Py_GT, ..., Py_GE to Py_LE.
00804  * Defined in object.c.
00805  */
00806 PyAPI_DATA(int) _Py_SwappedOp[];
00807 
00808 
00809 /*
00810 More conventions
00811 ================
00812 
00813 Argument Checking
00814 -----------------
00815 
00816 Functions that take objects as arguments normally don't check for nil
00817 arguments, but they do check the type of the argument, and return an
00818 error if the function doesn't apply to the type.
00819 
00820 Failure Modes
00821 -------------
00822 
00823 Functions may fail for a variety of reasons, including running out of
00824 memory.  This is communicated to the caller in two ways: an error string
00825 is set (see errors.h), and the function result differs: functions that
00826 normally return a pointer return NULL for failure, functions returning
00827 an integer return -1 (which could be a legal return value too!), and
00828 other functions return 0 for success and -1 for failure.
00829 Callers should always check for errors before using the result.  If
00830 an error was set, the caller must either explicitly clear it, or pass
00831 the error on to its caller.
00832 
00833 Reference Counts
00834 ----------------
00835 
00836 It takes a while to get used to the proper usage of reference counts.
00837 
00838 Functions that create an object set the reference count to 1; such new
00839 objects must be stored somewhere or destroyed again with Py_DECREF().
00840 Some functions that 'store' objects, such as PyTuple_SetItem() and
00841 PyList_SetItem(),
00842 don't increment the reference count of the object, since the most
00843 frequent use is to store a fresh object.  Functions that 'retrieve'
00844 objects, such as PyTuple_GetItem() and PyDict_GetItemString(), also
00845 don't increment
00846 the reference count, since most frequently the object is only looked at
00847 quickly.  Thus, to retrieve an object and store it again, the caller
00848 must call Py_INCREF() explicitly.
00849 
00850 NOTE: functions that 'consume' a reference count, like
00851 PyList_SetItem(), consume the reference even if the object wasn't
00852 successfully stored, to simplify error handling.
00853 
00854 It seems attractive to make other functions that take an object as
00855 argument consume a reference count; however, this may quickly get
00856 confusing (even the current practice is already confusing).  Consider
00857 it carefully, it may save lots of calls to Py_INCREF() and Py_DECREF() at
00858 times.
00859 */
00860 
00861 
00862 /* Trashcan mechanism, thanks to Christian Tismer.
00863 
00864 When deallocating a container object, it's possible to trigger an unbounded
00865 chain of deallocations, as each Py_DECREF in turn drops the refcount on "the
00866 next" object in the chain to 0.  This can easily lead to stack faults, and
00867 especially in threads (which typically have less stack space to work with).
00868 
00869 A container object that participates in cyclic gc can avoid this by
00870 bracketing the body of its tp_dealloc function with a pair of macros:
00871 
00872 static void
00873 mytype_dealloc(mytype *p)
00874 {
00875     ... declarations go here ...
00876 
00877     PyObject_GC_UnTrack(p);        // must untrack first
00878     Py_TRASHCAN_SAFE_BEGIN(p)
00879     ... The body of the deallocator goes here, including all calls ...
00880     ... to Py_DECREF on contained objects.                         ...
00881     Py_TRASHCAN_SAFE_END(p)
00882 }
00883 
00884 CAUTION:  Never return from the middle of the body!  If the body needs to
00885 "get out early", put a label immediately before the Py_TRASHCAN_SAFE_END
00886 call, and goto it.  Else the call-depth counter (see below) will stay
00887 above 0 forever, and the trashcan will never get emptied.
00888 
00889 How it works:  The BEGIN macro increments a call-depth counter.  So long
00890 as this counter is small, the body of the deallocator is run directly without
00891 further ado.  But if the counter gets large, it instead adds p to a list of
00892 objects to be deallocated later, skips the body of the deallocator, and
00893 resumes execution after the END macro.  The tp_dealloc routine then returns
00894 without deallocating anything (and so unbounded call-stack depth is avoided).
00895 
00896 When the call stack finishes unwinding again, code generated by the END macro
00897 notices this, and calls another routine to deallocate all the objects that
00898 may have been added to the list of deferred deallocations.  In effect, a
00899 chain of N deallocations is broken into N / PyTrash_UNWIND_LEVEL pieces,
00900 with the call stack never exceeding a depth of PyTrash_UNWIND_LEVEL.
00901 */
00902 
00903 PyAPI_FUNC(void) _PyTrash_deposit_object(PyObject*);
00904 PyAPI_FUNC(void) _PyTrash_destroy_chain(void);
00905 PyAPI_DATA(int) _PyTrash_delete_nesting;
00906 PyAPI_DATA(PyObject *) _PyTrash_delete_later;
00907 
00908 #define PyTrash_UNWIND_LEVEL 50
00909 
00910 #define Py_TRASHCAN_SAFE_BEGIN(op) \
00911     if (_PyTrash_delete_nesting < PyTrash_UNWIND_LEVEL) { \
00912         ++_PyTrash_delete_nesting;
00913         /* The body of the deallocator is here. */
00914 #define Py_TRASHCAN_SAFE_END(op) \
00915         --_PyTrash_delete_nesting; \
00916         if (_PyTrash_delete_later && _PyTrash_delete_nesting <= 0) \
00917             _PyTrash_destroy_chain(); \
00918     } \
00919     else \
00920         _PyTrash_deposit_object((PyObject*)op);
00921 
00922 #ifdef __cplusplus
00923 }
00924 #endif
00925 #endif /* !Py_OBJECT_H */