Commit c2b49cd8 authored by Robert Bradshaw's avatar Robert Bradshaw

Add pxi files for Python/C API (and a couple of other stubs)

Originally authored as part of SAGE by William Stein.
parent 758cad74
#####################################################################
#
# These are the "SageX" pxi files for (most of) the Python/C API.
#
# SageX = SAGE Pyrex, which is a fork of Pyrex for use in SAGE.
#
# REFERENCE COUNTING:
#
# JUST TO SCARE YOU:
# If you are going to use any of the Python/C API in your SageX
# program, you might be responsible for doing reference counting.
# Read http://docs.python.org/api/refcounts.html which is so
# important I've copied it below.
#
# For all the declaration below, whenver the Py_ function returns
# a *new reference* to a PyObject*, the return type is "object".
# When the function returns a borrowed reference, the return
# type is PyObject*. When SageX sees "object" as a return type
# it doesn't increment the reference count. When it sees PyObject*
# in order to use the result you must explicitly cast to <object>,
# and when you do that SageX increments the reference count wether
# you want it to or not, forcing you to an explicit DECREF (or leak memory).
# To avoid this we make the above convention. Note, you can
# always locally override this convention by putting something like
#
# cdef extern from "Python.h":
# PyObject* PyNumber_Add(PyObject *o1, PyObject *o2)
#
# in your file after any .pxi includes. SageX will use the latest
# declaration.
#
# SageX takes care of this automatically for anything of type object.
## More precisely, I think the correct convention for
## using the Python/C API from Pyrex is as follows.
##
## (1) Declare all input arguments as type "object". This way no explicit
## <PyObject*> casting is needed, and moreover Pyrex doesn't generate
## any funny reference counting.
## (2) Declare output as object if a new reference is returned.
## (3) Declare output as PyObject* if a borrowed reference is returned.
##
## This way when you call objects, no cast is needed, and if the api
## calls returns a new reference (which is about 95% of them), then
## you can just assign to a variable of type object. With borrowed
## references if you do an explicit typecast to <object>, Pyrex generates an
## INCREF and DECREF so you have to be careful. However, you got a
## borrowed reference in this case, so there's got to be another reference
## to your object, so you're OK, as long as you relealize this
## and use the result of an explicit cast to <object> as a borrowed
## reference (and you can call Py_INCREF if you want to turn it
## into another reference for some reason).
#
# "The reference count is important because today's computers have
# a finite (and often severely limited) memory size; it counts how
# many different places there are that have a reference to an
# object. Such a place could be another object, or a global (or
# static) C variable, or a local variable in some C function. When
# an object's reference count becomes zero, the object is
# deallocated. If it contains references to other objects, their
# reference count is decremented. Those other objects may be
# deallocated in turn, if this decrement makes their reference
# count become zero, and so on. (There's an obvious problem with
# objects that reference each other here; for now, the solution is
# ``don't do that.'')
#
# Reference counts are always manipulated explicitly. The normal
# way is to use the macro Py_INCREF() to increment an object's
# reference count by one, and Py_DECREF() to decrement it by
# one. The Py_DECREF() macro is considerably more complex than the
# incref one, since it must check whether the reference count
# becomes zero and then cause the object's deallocator to be
# called. The deallocator is a function pointer contained in the
# object's type structure. The type-specific deallocator takes
# care of decrementing the reference counts for other objects
# contained in the object if this is a compound object type, such
# as a list, as well as performing any additional finalization
# that's needed. There's no chance that the reference count can
# overflow; at least as many bits are used to hold the reference
# count as there are distinct memory locations in virtual memory
# (assuming sizeof(long) >= sizeof(char*)). Thus, the reference
# count increment is a simple operation.
#
# It is not necessary to increment an object's reference count for
# every local variable that contains a pointer to an object. In
# theory, the object's reference count goes up by one when the
# variable is made to point to it and it goes down by one when the
# variable goes out of scope. However, these two cancel each other
# out, so at the end the reference count hasn't changed. The only
# real reason to use the reference count is to prevent the object
# from being deallocated as long as our variable is pointing to
# it. If we know that there is at least one other reference to the
# object that lives at least as long as our variable, there is no
# need to increment the reference count temporarily. An important
# situation where this arises is in objects that are passed as
# arguments to C functions in an extension module that are called
# from Python; the call mechanism guarantees to hold a reference
# to every argument for the duration of the call.
#
# However, a common pitfall is to extract an object from a list
# and hold on to it for a while without incrementing its reference
# count. Some other operation might conceivably remove the object
# from the list, decrementing its reference count and possible
# deallocating it. The real danger is that innocent-looking
# operations may invoke arbitrary Python code which could do this;
# there is a code path which allows control to flow back to the
# user from a Py_DECREF(), so almost any operation is potentially
# dangerous.
#
# A safe approach is to always use the generic operations
# (functions whose name begins with "PyObject_", "PyNumber_",
# "PySequence_" or "PyMapping_"). These operations always
# increment the reference count of the object they return. This
# leaves the caller with the responsibility to call Py_DECREF()
# when they are done with the result; this soon becomes second
# nature.
#
# Now you should read http://docs.python.org/api/refcountDetails.html
# just to be sure you understand what is going on.
#
#################################################################
cdef extern from "Python.h":
ctypedef void PyObject
ctypedef void PyTypeObject
ctypedef struct FILE
include 'python_ref.pxi'
include 'python_exc.pxi'
include 'python_module.pxi'
include 'python_mem.pxi'
include 'python_tuple.pxi'
include 'python_list.pxi'
include 'python_object.pxi'
include 'python_sequence.pxi'
include 'python_mapping.pxi'
include 'python_iterator.pxi'
include 'python_type.pxi'
include 'python_number.pxi'
include 'python_int.pxi'
include 'python_bool.pxi'
include 'python_long.pxi'
include 'python_float.pxi'
include 'python_complex.pxi'
include 'python_string.pxi'
include 'python_dict.pxi'
include 'python_instance.pxi'
include 'python_function.pxi'
include 'python_method.pxi'
include 'python_set.pxi'
cdef extern from "Python.h":
ctypedef void PyObject
############################################################################
# 7.2.2 Boolean Objects
############################################################################
# Booleans in Python are implemented as a subclass of
# integers. There are only two booleans, Py_False and Py_True. As
# such, the normal creation and deletion functions don't apply to
# booleans. The following macros are available, however.
bint PyBool_Check(object o)
# Return true if o is of type PyBool_Type.
#PyObject* Py_False
# The Python False object. This object has no methods. It needs to
# be treated just like any other object with respect to reference
# counts.
#PyObject* Py_True
# The Python True object. This object has no methods. It needs to
# be treated just like any other object with respect to reference
# counts.
# Py_RETURN_FALSE
# Return Py_False from a function, properly incrementing its reference count.
# Py_RETURN_TRUE
# Return Py_True from a function, properly incrementing its reference count.
object PyBool_FromLong(long v)
# Return value: New reference.
# Return a new reference to Py_True or Py_False depending on the truth value of v.
cdef extern from "Python.h":
ctypedef void PyObject
ctypedef struct Py_complex
############################################################################
# 7.2.5.2 Complex Numbers as Python Objects
############################################################################
# PyComplexObject
# This subtype of PyObject represents a Python complex number object.
# PyTypeObject PyComplex_Type
# This instance of PyTypeObject represents the Python complex
# number type. It is the same object as complex and
# types.ComplexType.
bint PyComplex_Check(object p)
# Return true if its argument is a PyComplexObject or a subtype of
# PyComplexObject.
bint PyComplex_CheckExact(object p)
# Return true if its argument is a PyComplexObject, but not a subtype of PyComplexObject.
object PyComplex_FromCComplex(Py_complex v)
# Return value: New reference.
# Create a new Python complex number object from a C Py_complex value.
object PyComplex_FromDoubles(double real, double imag)
# Return value: New reference.
# Return a new PyComplexObject object from real and imag.
double PyComplex_RealAsDouble(object op)
# Return the real part of op as a C double.
double PyComplex_ImagAsDouble(object op)
# Return the imaginary part of op as a C double.
Py_complex PyComplex_AsCComplex(object op)
# Return the Py_complex value of the complex number op.
cdef extern from "Python.h":
ctypedef void PyObject
############################################################################
# 7.4.1 Dictionary Objects
############################################################################
# PyDictObject
# This subtype of PyObject represents a Python dictionary object.
# PyTypeObject PyDict_Type
# This instance of PyTypeObject represents the Python dictionary type. This is exposed to Python programs as dict and types.DictType.
bint PyDict_Check(object p)
# Return true if p is a dict object or an instance of a subtype of
# the dict type.
bint PyDict_CheckExact(object p)
# Return true if p is a dict object, but not an instance of a
# subtype of the dict type.
object PyDict_New()
# Return value: New reference.
# Return a new empty dictionary, or NULL on failure.
object PyDictProxy_New(object dict)
# Return value: New reference.
# Return a proxy object for a mapping which enforces read-only
# behavior. This is normally used to create a proxy to prevent
# modification of the dictionary for non-dynamic class types.
void PyDict_Clear(object p)
# Empty an existing dictionary of all key-value pairs.
int PyDict_Contains(object p, object key)
# Determine if dictionary p contains key. If an item in p is
# matches key, return 1, otherwise return 0. On error, return
# -1. This is equivalent to the Python expression "key in p".
object PyDict_Copy(object p)
# Return value: New reference.
# Return a new dictionary that contains the same key-value pairs as p.
int PyDict_SetItem(object p, object key, object val)
# Insert value into the dictionary p with a key of key. key must
# be hashable; if it isn't, TypeError will be raised. Return 0 on
# success or -1 on failure.
int PyDict_SetItemString(object p, char *key, object val)
# Insert value into the dictionary p using key as a key. key
# should be a char*. The key object is created using
# PyString_FromString(key). Return 0 on success or -1 on failure.
int PyDict_DelItem(object p, object key)
# Remove the entry in dictionary p with key key. key must be
# hashable; if it isn't, TypeError is raised. Return 0 on success
# or -1 on failure.
int PyDict_DelItemString(object p, char *key)
# Remove the entry in dictionary p which has a key specified by
# the string key. Return 0 on success or -1 on failure.
PyObject* PyDict_GetItem(object p, object key)
# Return value: Borrowed reference.
# Return the object from dictionary p which has a key key. Return
# NULL if the key key is not present, but without setting an
# exception.
PyObject* PyDict_GetItemString(object p, char *key)
# Return value: Borrowed reference.
# This is the same as PyDict_GetItem(), but key is specified as a
# char*, rather than a PyObject*.
object PyDict_Items(object p)
# Return value: New reference.
# Return a PyListObject containing all the items from the
# dictionary, as in the dictionary method items() (see the Python
# Library Reference).
object PyDict_Keys(object p)
# Return value: New reference.
# Return a PyListObject containing all the keys from the
# dictionary, as in the dictionary method keys() (see the Python
# Library Reference).
object PyDict_Values(object p)
# Return value: New reference.
# Return a PyListObject containing all the values from the
# dictionary p, as in the dictionary method values() (see the
# Python Library Reference).
Py_ssize_t PyDict_Size(object p)
# Return the number of items in the dictionary. This is equivalent to "len(p)" on a dictionary.
int PyDict_Next(object p, Py_ssize_t *ppos, PyObject* *pkey, PyObject* *pvalue)
# Iterate over all key-value pairs in the dictionary p. The int
# referred to by ppos must be initialized to 0 prior to the first
# call to this function to start the iteration; the function
# returns true for each pair in the dictionary, and false once all
# pairs have been reported. The parameters pkey and pvalue should
# either point to PyObject* variables that will be filled in with
# each key and value, respectively, or may be NULL. Any references
# returned through them are borrowed. ppos should not be altered
# during iteration. Its value represents offsets within the
# internal dictionary structure, and since the structure is
# sparse, the offsets are not consecutive.
# For example:
#
#object key, *value;
#int pos = 0;
#
#while (PyDict_Next(self->dict, &pos, &key, &value)) {
# /* do something interesting with the values... */
# ...
#}
# The dictionary p should not be mutated during iteration. It is
# safe (since Python 2.1) to modify the values of the keys as you
# iterate over the dictionary, but only so long as the set of keys
# does not change. For example:
# object key, *value;
# int pos = 0;
# while (PyDict_Next(self->dict, &pos, &key, &value)) {
# int i = PyInt_AS_LONG(value) + 1;
# object o = PyInt_FromLong(i);
# if (o == NULL)
# return -1;
# if (PyDict_SetItem(self->dict, key, o) < 0) {
# Py_DECREF(o);
# return -1;
# }
# Py_DECREF(o);
# }
int PyDict_Merge(object a, object b, int override)
# Iterate over mapping object b adding key-value pairs to
# dictionary a. b may be a dictionary, or any object supporting
# PyMapping_Keys() and PyObject_GetItem(). If override is true,
# existing pairs in a will be replaced if a matching key is found
# in b, otherwise pairs will only be added if there is not a
# matching key in a. Return 0 on success or -1 if an exception was
# raised.
int PyDict_Update(object a, object b)
# This is the same as PyDict_Merge(a, b, 1) in C, or a.update(b)
# in Python. Return 0 on success or -1 if an exception was raised.
int PyDict_MergeFromSeq2(object a, object seq2, int override)
# Update or merge into dictionary a, from the key-value pairs in
# seq2. seq2 must be an iterable object producing iterable objects
# of length 2, viewed as key-value pairs. In case of duplicate
# keys, the last wins if override is true, else the first
# wins. Return 0 on success or -1 if an exception was
# raised. Equivalent Python (except for the return value):
#
#def PyDict_MergeFromSeq2(a, seq2, override):
# for key, value in seq2:
# if override or key not in a:
# a[key] = value
This diff is collapsed.
cdef extern from "Python.h":
ctypedef void PyObject
############################################################################
# 7.2.3
############################################################################
# PyFloatObject
# This subtype of PyObject represents a Python floating point object.
# PyTypeObject PyFloat_Type
# This instance of PyTypeObject represents the Python floating point type. This is the same object as float and types.FloatType.
bint PyFloat_Check(object p)
# Return true if its argument is a PyFloatObject or a subtype of
# PyFloatObject.
bint PyFloat_CheckExact(object p)
# Return true if its argument is a PyFloatObject, but not a
# subtype of PyFloatObject.
object PyFloat_FromString(object str, char **pend)
# Return value: New reference.
# Create a PyFloatObject object based on the string value in str,
# or NULL on failure. The pend argument is ignored. It remains
# only for backward compatibility.
object PyFloat_FromDouble(double v)
# Return value: New reference.
# Create a PyFloatObject object from v, or NULL on failure.
double PyFloat_AsDouble(object pyfloat)
# Return a C double representation of the contents of pyfloat.
double PyFloat_AS_DOUBLE(object pyfloat)
# Return a C double representation of the contents of pyfloat, but without error checking.
cdef extern from "Python.h":
ctypedef void PyObject
############################################################################
# 7.5.3 Function Objects
############################################################################
# There are a few functions specific to Python functions.
# PyFunctionObject
# The C structure used for functions.
# PyTypeObject PyFunction_Type
# This is an instance of PyTypeObject and represents the Python
# function type. It is exposed to Python programmers as
# types.FunctionType.
bint PyFunction_Check(object o)
# Return true if o is a function object (has type
# PyFunction_Type). The parameter must not be NULL.
object PyFunction_New(object code, object globals)
# Return value: New reference.
# Return a new function object associated with the code object
# code. globals must be a dictionary with the global variables
# accessible to the function.
# The function's docstring, name and __module__ are retrieved from
# the code object, the argument defaults and closure are set to
# NULL.
PyObject* PyFunction_GetCode(object op)
# Return value: Borrowed reference.
# Return the code object associated with the function object op.
PyObject* PyFunction_GetGlobals(object op)
# Return value: Borrowed reference.
# Return the globals dictionary associated with the function object op.
PyObject* PyFunction_GetModule(object op)
# Return value: Borrowed reference.
# Return the __module__ attribute of the function object op. This
# is normally a string containing the module name, but can be set
# to any other object by Python code.
PyObject* PyFunction_GetDefaults(object op)
# Return value: Borrowed reference.
# Return the argument default values of the function object
# op. This can be a tuple of arguments or NULL.
int PyFunction_SetDefaults(object op, object defaults)
# Set the argument default values for the function object
# op. defaults must be Py_None or a tuple.
# Raises SystemError and returns -1 on failure.
PyObject* PyFunction_GetClosure(object op)
# Return value: Borrowed reference.
# Return the closure associated with the function object op. This
# can be NULL or a tuple of cell objects.
int PyFunction_SetClosure(object op, object closure)
# Set the closure associated with the function object op. closure
# must be Py_None or a tuple of cell objects.
# Raises SystemError and returns -1 on failure.
cdef extern from "Python.h":
ctypedef void PyObject
############################################################################
# 7.5.2 Instance Objects
############################################################################
# PyTypeObject PyInstance_Type
# Type object for class instances.
# int PyInstance_Check(PyObject *obj)
# Return true if obj is an instance.
object PyInstance_New(PyObject* cls, object arg, object kw)
# Return value: New reference.
# Create a new instance of a specific class. The parameters arg
# and kw are used as the positional and keyword parameters to the
# object's constructor.
object PyInstance_NewRaw(object cls, object dict)
# Return value: New reference.
# Create a new instance of a specific class without calling its
# constructor. class is the class of new object. The dict
# parameter will be used as the object's __dict__; if NULL, a new
# dictionary will be created for the instance.
cdef extern from "Python.h":
ctypedef void PyObject
############################################################################
# Integer Objects
############################################################################
# PyTypeObject PyInt_Type
# This instance of PyTypeObject represents the Python plain
# integer type. This is the same object as int and types.IntType.
bint PyInt_Check(object o)
# Return true if o is of type PyInt_Type or a subtype of
# PyInt_Type.
bint PyInt_CheckExact(object o)
# Return true if o is of type PyInt_Type, but not a subtype of
# PyInt_Type.
object PyInt_FromString(char *str, char **pend, int base)
# Return value: New reference.
# Return a new PyIntObject or PyLongObject based on the string
# value in str, which is interpreted according to the radix in
# base. If pend is non-NULL, *pend will point to the first
# character in str which follows the representation of the
# number. If base is 0, the radix will be determined based on the
# leading characters of str: if str starts with '0x' or '0X',
# radix 16 will be used; if str starts with '0', radix 8 will be
# used; otherwise radix 10 will be used. If base is not 0, it must
# be between 2 and 36, inclusive. Leading spaces are ignored. If
# there are no digits, ValueError will be raised. If the string
# represents a number too large to be contained within the
# machine's long int type and overflow warnings are being
# suppressed, a PyLongObject will be returned. If overflow
# warnings are not being suppressed, NULL will be returned in this
# case.
object PyInt_FromLong(long ival)
# Return value: New reference.
# Create a new integer object with a value of ival.
# The current implementation keeps an array of integer objects for
# all integers between -5 and 256, when you create an int in that
# range you actually just get back a reference to the existing
# object. So it should be possible to change the value of 1. I
# suspect the behaviour of Python in this case is undefined. :-)
object PyInt_FromSsize_t(Py_ssize_t ival)
# Return value: New reference.
# Create a new integer object with a value of ival. If the value
# exceeds LONG_MAX, a long integer object is returned.
long PyInt_AsLong(object io)
# Will first attempt to cast the object to a PyIntObject, if it is
# not already one, and then return its value. If there is an
# error, -1 is returned, and the caller should check
# PyErr_Occurred() to find out whether there was an error, or
# whether the value just happened to be -1.
long PyInt_AS_LONG(object io)
# Return the value of the object io. No error checking is performed.
unsigned long PyInt_AsUnsignedLongMask(object io)
# Will first attempt to cast the object to a PyIntObject or
# PyLongObject, if it is not already one, and then return its
# value as unsigned long. This function does not check for
# overflow.
ctypedef unsigned long long PY_LONG_LONG
PY_LONG_LONG PyInt_AsUnsignedLongLongMask(object io)
# Will first attempt to cast the object to a PyIntObject or
# PyLongObject, if it is not already one, and then return its
# value as unsigned long long, without checking for overflow.
Py_ssize_t PyInt_AsSsize_t(object io)
# Will first attempt to cast the object to a PyIntObject or
# PyLongObject, if it is not already one, and then return its
# value as Py_ssize_t.
long PyInt_GetMax()
# Return the system's idea of the largest integer it can handle
# (LONG_MAX, as defined in the system header files).
cdef extern from "Python.h":
############################################################################
# 6.5 Iterator Protocol
############################################################################
int PyIter_Check(object o)
# Return true if the object o supports the iterator protocol.
object PyIter_Next(object o)
# Return value: New reference.
# Return the next value from the iteration o. If the object is an
# iterator, this retrieves the next value from the iteration, and
# returns NULL with no exception set if there are no remaining
# items. If the object is not an iterator, TypeError is raised, or
# if there is an error in retrieving the item, returns NULL and
# passes along the exception.
# To write a loop which iterates over an iterator, the C code should look something like this:
# PyObject *iterator = PyObject_GetIter(obj);
# PyObject *item;
# if (iterator == NULL) {
# /* propagate error */
# }
# while (item = PyIter_Next(iterator)) {
# /* do something with item */
# ...
# /* release reference when done */
# Py_DECREF(item);
# }
# Py_DECREF(iterator);
# if (PyErr_Occurred()) {
# /* propagate error */
# }
# else {
# /* continue doing useful work */
# }
cdef extern from "Python.h":
ctypedef void PyObject
############################################################################
# Lists
############################################################################
object PyList_New(Py_ssize_t len)
# Return a new list of length len on success, or NULL on
# failure. Note: If length is greater than zero, the returned list
# object's items are set to NULL. Thus you cannot use abstract API
# functions such as PySequence_SetItem() or expose the object to
# Python code before setting all items to a real object with
# PyList_SetItem().
bint PyList_Check(object p)
# Return true if p is a list object or an instance of a subtype of the list type.
bint PyList_CheckExact(object p)
# Return true if p is a list object, but not an instance of a subtype of the list type.
Py_ssize_t PyList_Size(object list)
# Return the length of the list object in list; this is equivalent to "len(list)" on a list object.
Py_ssize_t PyList_GET_SIZE(object list)
# Macro form of PyList_Size() without error checking.
PyObject* PyList_GetItem(object list, Py_ssize_t index)
# Return value: Borrowed reference.
# Return the object at position pos in the list pointed to by
# p. The position must be positive, indexing from the end of the
# list is not supported. If pos is out of bounds, return NULL and
# set an IndexError exception.
PyObject* PyList_GET_ITEM(object list, Py_ssize_t i)
# Return value: Borrowed reference.
# Macro form of PyList_GetItem() without error checking.
int PyList_SetItem(object list, Py_ssize_t index, object item)
# Set the item at index index in list to item. Return 0 on success
# or -1 on failure. Note: This function ``steals'' a reference to
# item and discards a reference to an item already in the list at
# the affected position.
void PyList_SET_ITEM(object list, Py_ssize_t i, object o)
# Macro form of PyList_SetItem() without error checking. This is
# normally only used to fill in new lists where there is no
# previous content. Note: This function ``steals'' a reference to
# item, and, unlike PyList_SetItem(), does not discard a reference
# to any item that it being replaced; any reference in list at
# position i will be *leaked*.
int PyList_Insert(object list, Py_ssize_t index, object item)
# Insert the item item into list list in front of index
# index. Return 0 if successful; return -1 and set an exception if
# unsuccessful. Analogous to list.insert(index, item).
int PyList_Append(object list, object item)
# Append the object item at the end of list list. Return 0 if
# successful; return -1 and set an exception if
# unsuccessful. Analogous to list.append(item).
object PyList_GetSlice(object list, Py_ssize_t low, Py_ssize_t high)
# Return value: New reference.
# Return a list of the objects in list containing the objects
# between low and high. Return NULL and set an exception if
# unsuccessful. Analogous to list[low:high].
int PyList_SetSlice(object list, Py_ssize_t low, Py_ssize_t high, object itemlist)
# Set the slice of list between low and high to the contents of
# itemlist. Analogous to list[low:high] = itemlist. The itemlist
# may be NULL, indicating the assignment of an empty list (slice
# deletion). Return 0 on success, -1 on failure.
int PyList_Sort(object list)
# Sort the items of list in place. Return 0 on success, -1 on
# failure. This is equivalent to "list.sort()".
int PyList_Reverse(object list)
# Reverse the items of list in place. Return 0 on success, -1 on
# failure. This is the equivalent of "list.reverse()".
object PyList_AsTuple(object list)
# Return value: New reference.
# Return a new tuple object containing the contents of list;
# equivalent to "tuple(list)".
cdef extern from "Python.h":
ctypedef void PyObject
ctypedef long PY_LONG_LONG
############################################################################
# 7.2.3 Long Integer Objects
############################################################################
# PyLongObject
# This subtype of PyObject represents a Python long integer object.
# PyTypeObject PyLong_Type
# This instance of PyTypeObject represents the Python long integer
# type. This is the same object as long and types.LongType.
bint PyLong_Check(object p)
# Return true if its argument is a PyLongObject or a subtype of PyLongObject.
bint PyLong_CheckExact(object p)
# Return true if its argument is a PyLongObject, but not a subtype of PyLongObject.
object PyLong_FromLong(long v)
# Return value: New reference.
# Return a new PyLongObject object from v, or NULL on failure.
object PyLong_FromUnsignedLong(unsigned long v)
# Return value: New reference.
# Return a new PyLongObject object from a C unsigned long, or NULL on failure.
object PyLong_FromLongLong(PY_LONG_LONG v)
# Return value: New reference.
# Return a new PyLongObject object from a C long long, or NULL on failure.
object PyLong_FromUnsignedLongLong(PY_LONG_LONG v)
#PyObject* PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG v)
# Return value: New reference.
# Return a new PyLongObject object from a C unsigned long long, or NULL on failure.
object PyLong_FromDouble(double v)
# Return value: New reference.
# Return a new PyLongObject object from the integer part of v, or NULL on failure.
object PyLong_FromString(char *str, char **pend, int base)
# Return value: New reference.
# Return a new PyLongObject based on the string value in str,
# which is interpreted according to the radix in base. If pend is
# non-NULL, *pend will point to the first character in str which
# follows the representation of the number. If base is 0, the
# radix will be determined based on the leading characters of str:
# if str starts with '0x' or '0X', radix 16 will be used; if str
# starts with '0', radix 8 will be used; otherwise radix 10 will
# be used. If base is not 0, it must be between 2 and 36,
# inclusive. Leading spaces are ignored. If there are no digits,
# ValueError will be raised.
# object PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
# Return value: New reference.
# Convert a sequence of Unicode digits to a Python long integer
# value. The first parameter, u, points to the first character of
# the Unicode string, length gives the number of characters, and
# base is the radix for the conversion. The radix must be in the
# range [2, 36]; if it is out of range, ValueError will be
# raised.
object PyLong_FromVoidPtr(void *p)
# Return value: New reference.
# Create a Python integer or long integer from the pointer p. The
# pointer value can be retrieved from the resulting value using
# PyLong_AsVoidPtr(). If the integer is larger than LONG_MAX, a
# positive long integer is returned.
long PyLong_AsLong(object pylong)
# Return a C long representation of the contents of pylong. If
# pylong is greater than LONG_MAX, an OverflowError is raised.
unsigned long PyLong_AsUnsignedLong(object pylong)
# Return a C unsigned long representation of the contents of
# pylong. If pylong is greater than ULONG_MAX, an OverflowError is
# raised.
PY_LONG_LONG PyLong_AsLongLong(object pylong)
# Return a C long long from a Python long integer. If pylong
# cannot be represented as a long long, an OverflowError will be
# raised.
PY_LONG_LONG PyLong_AsUnsignedLongLong(object pylong)
#unsigned PY_LONG_LONG PyLong_AsUnsignedLongLong(object pylong)
# Return a C unsigned long long from a Python long integer. If
# pylong cannot be represented as an unsigned long long, an
# OverflowError will be raised if the value is positive, or a
# TypeError will be raised if the value is negative.
unsigned long PyLong_AsUnsignedLongMask(object io)
# Return a C unsigned long from a Python long integer, without
# checking for overflow.
PY_LONG_LONG PyLong_AsUnsignedLongLongMask(object io)
#unsigned PY_LONG_LONG PyLong_AsUnsignedLongLongMask(object io)
# Return a C unsigned long long from a Python long integer,
# without checking for overflow.
double PyLong_AsDouble(object pylong)
# Return a C double representation of the contents of pylong. If
# pylong cannot be approximately represented as a double, an
# OverflowError exception is raised and -1.0 will be returned.
void* PyLong_AsVoidPtr(object pylong)
# Convert a Python integer or long integer pylong to a C void
# pointer. If pylong cannot be converted, an OverflowError will be
# raised. This is only assured to produce a usable void pointer
# for values created with PyLong_FromVoidPtr(). For values outside
# 0..LONG_MAX, both signed and unsigned integers are acccepted.
cdef extern from "Python.h":
ctypedef void PyObject
############################################################################
# 6.4 Mapping Protocol
############################################################################
bint PyMapping_Check(object o)
# Return 1 if the object provides mapping protocol, and 0
# otherwise. This function always succeeds.
Py_ssize_t PyMapping_Length(object o)
# Returns the number of keys in object o on success, and -1 on
# failure. For objects that do not provide mapping protocol, this
# is equivalent to the Python expression "len(o)".
int PyMapping_DelItemString(object o, char *key)
# Remove the mapping for object key from the object o. Return -1
# on failure. This is equivalent to the Python statement "del
# o[key]".
int PyMapping_DelItem(object o, object key)
# Remove the mapping for object key from the object o. Return -1
# on failure. This is equivalent to the Python statement "del
# o[key]".
bint PyMapping_HasKeyString(object o, char *key)
# On success, return 1 if the mapping object has the key key and 0
# otherwise. This is equivalent to the Python expression
# "o.has_key(key)". This function always succeeds.
bint PyMapping_HasKey(object o, object key)
# Return 1 if the mapping object has the key key and 0
# otherwise. This is equivalent to the Python expression
# "o.has_key(key)". This function always succeeds.
object PyMapping_Keys(object o)
# Return value: New reference.
# On success, return a list of the keys in object o. On failure,
# return NULL. This is equivalent to the Python expression
# "o.keys()".
object PyMapping_Values(object o)
# Return value: New reference.
# On success, return a list of the values in object o. On failure,
# return NULL. This is equivalent to the Python expression
# "o.values()".
object PyMapping_Items(object o)
# Return value: New reference.
# On success, return a list of the items in object o, where each
# item is a tuple containing a key-value pair. On failure, return
# NULL. This is equivalent to the Python expression "o.items()".
object PyMapping_GetItemString(object o, char *key)
# Return value: New reference.
# Return element of o corresponding to the object key or NULL on
# failure. This is the equivalent of the Python expression
# "o[key]".
int PyMapping_SetItemString(object o, char *key, object v)
# Map the object key to the value v in object o. Returns -1 on
# failure. This is the equivalent of the Python statement "o[key]
# = v".
cdef extern from "Python.h":
ctypedef unsigned long size_t
#####################################################################
# 9.2 Memory Interface
#####################################################################
# You are definitely *supposed* to use these: "In most situations,
# however, it is recommended to allocate memory from the Python
# heap specifically because the latter is under control of the
# Python memory manager. For example, this is required when the
# interpreter is extended with new object types written in
# C. Another reason for using the Python heap is the desire to
# inform the Python memory manager about the memory needs of the
# extension module. Even when the requested memory is used
# exclusively for internal, highly-specific purposes, delegating
# all memory requests to the Python memory manager causes the
# interpreter to have a more accurate image of its memory
# footprint as a whole. Consequently, under certain circumstances,
# the Python memory manager may or may not trigger appropriate
# actions, like garbage collection, memory compaction or other
# preventive procedures. Note that by using the C library
# allocator as shown in the previous example, the allocated memory
# for the I/O buffer escapes completely the Python memory
# manager."
# The following function sets, modeled after the ANSI C standard,
# but specifying behavior when requesting zero bytes, are
# available for allocating and releasing memory from the Python
# heap:
void* PyMem_Malloc(size_t n)
# Allocates n bytes and returns a pointer of type void* to the
# allocated memory, or NULL if the request fails. Requesting zero
# bytes returns a distinct non-NULL pointer if possible, as if
# PyMem_Malloc(1) had been called instead. The memory will not
# have been initialized in any way.
void* PyMem_Realloc(void *p, size_t n)
# Resizes the memory block pointed to by p to n bytes. The
# contents will be unchanged to the minimum of the old and the new
# sizes. If p is NULL, the call is equivalent to PyMem_Malloc(n);
# else if n is equal to zero, the memory block is resized but is
# not freed, and the returned pointer is non-NULL. Unless p is
# NULL, it must have been returned by a previous call to
# PyMem_Malloc() or PyMem_Realloc().
void PyMem_Free(void *p)
# Frees the memory block pointed to by p, which must have been
# returned by a previous call to PyMem_Malloc() or
# PyMem_Realloc(). Otherwise, or if PyMem_Free(p) has been called
# before, undefined behavior occurs. If p is NULL, no operation is
# performed.
# The following type-oriented macros are provided for
# convenience. Note that TYPE refers to any C type.
# TYPE* PyMem_New(TYPE, size_t n)
# Same as PyMem_Malloc(), but allocates (n * sizeof(TYPE)) bytes
# of memory. Returns a pointer cast to TYPE*. The memory will not
# have been initialized in any way.
# TYPE* PyMem_Resize(void *p, TYPE, size_t n)
# Same as PyMem_Realloc(), but the memory block is resized to (n *
# sizeof(TYPE)) bytes. Returns a pointer cast to TYPE*.
void PyMem_Del(void *p)
# Same as PyMem_Free().
# In addition, the following macro sets are provided for calling
# the Python memory allocator directly, without involving the C
# API functions listed above. However, note that their use does
# not preserve binary compatibility across Python versions and is
# therefore deprecated in extension modules.
# PyMem_MALLOC(), PyMem_REALLOC(), PyMem_FREE().
# PyMem_NEW(), PyMem_RESIZE(), PyMem_DEL().
cdef extern from "Python.h":
ctypedef void PyObject
############################################################################
# 7.5.4 Method Objects
############################################################################
# There are some useful functions that are useful for working with method objects.
# PyTypeObject PyMethod_Type
# This instance of PyTypeObject represents the Python method type. This is exposed to Python programs as types.MethodType.
bint PyMethod_Check(object o)
# Return true if o is a method object (has type
# PyMethod_Type). The parameter must not be NULL.
object PyMethod_New(object func, object self, object cls)
# Return value: New reference.
# Return a new method object, with func being any callable object;
# this is the function that will be called when the method is
# called. If this method should be bound to an instance, self
# should be the instance and class should be the class of self,
# otherwise self should be NULL and class should be the class
# which provides the unbound method..
PyObject* PyMethod_Class(object meth)
# Return value: Borrowed reference.
# Return the class object from which the method meth was created;
# if this was created from an instance, it will be the class of
# the instance.
PyObject* PyMethod_GET_CLASS(object meth)
# Return value: Borrowed reference.
# Macro version of PyMethod_Class() which avoids error checking.
PyObject* PyMethod_Function(object meth)
# Return value: Borrowed reference.
# Return the function object associated with the method meth.
PyObject* PyMethod_GET_FUNCTION(object meth)
# Return value: Borrowed reference.
# Macro version of PyMethod_Function() which avoids error checking.
PyObject* PyMethod_Self(object meth)
# Return value: Borrowed reference.
# Return the instance associated with the method meth if it is bound, otherwise return NULL.
PyObject* PyMethod_GET_SELF(object meth)
# Return value: Borrowed reference.
# Macro version of PyMethod_Self() which avoids error checking.
cdef extern from "Python.h":
ctypedef void PyObject
ctypedef struct _inittab
#####################################################################
# 5.3 Importing Modules
#####################################################################
object PyImport_ImportModule(char *name)
# Return value: New reference.
# This is a simplified interface to PyImport_ImportModuleEx()
# below, leaving the globals and locals arguments set to
# NULL. When the name argument contains a dot (when it specifies a
# submodule of a package), the fromlist argument is set to the
# list ['*'] so that the return value is the named module rather
# than the top-level package containing it as would otherwise be
# the case. (Unfortunately, this has an additional side effect
# when name in fact specifies a subpackage instead of a submodule:
# the submodules specified in the package's __all__ variable are
# loaded.) Return a new reference to the imported module, or NULL
# with an exception set on failure.
object PyImport_ImportModuleEx(char *name, object globals, object locals, object fromlist)
# Return value: New reference.
# Import a module. This is best described by referring to the
# built-in Python function __import__(), as the standard
# __import__() function calls this function directly.
# The return value is a new reference to the imported module or
# top-level package, or NULL with an exception set on failure
# (before Python 2.4, the module may still be created in this
# case). Like for __import__(), the return value when a submodule
# of a package was requested is normally the top-level package,
# unless a non-empty fromlist was given. Changed in version 2.4:
# failing imports remove incomplete module objects.
object PyImport_Import(object name)
# Return value: New reference.
# This is a higher-level interface that calls the current ``import
# hook function''. It invokes the __import__() function from the
# __builtins__ of the current globals. This means that the import
# is done using whatever import hooks are installed in the current
# environment, e.g. by rexec or ihooks.
object PyImport_ReloadModule(object m)
# Return value: New reference.
# Reload a module. This is best described by referring to the
# built-in Python function reload(), as the standard reload()
# function calls this function directly. Return a new reference to
# the reloaded module, or NULL with an exception set on failure
# (the module still exists in this case).
PyObject* PyImport_AddModule(char *name)
# Return value: Borrowed reference.
# Return the module object corresponding to a module name. The
# name argument may be of the form package.module. First check the
# modules dictionary if there's one there, and if not, create a
# new one and insert it in the modules dictionary. Return NULL
# with an exception set on failure. Note: This function does not
# load or import the module; if the module wasn't already loaded,
# you will get an empty module object. Use PyImport_ImportModule()
# or one of its variants to import a module. Package structures
# implied by a dotted name for name are not created if not already
# present.
object PyImport_ExecCodeModule(char *name, object co)
# Return value: New reference.
# Given a module name (possibly of the form package.module) and a
# code object read from a Python bytecode file or obtained from
# the built-in function compile(), load the module. Return a new
# reference to the module object, or NULL with an exception set if
# an error occurred. Name is removed from sys.modules in error
# cases, and even if name was already in sys.modules on entry to
# PyImport_ExecCodeModule(). Leaving incompletely initialized
# modules in sys.modules is dangerous, as imports of such modules
# have no way to know that the module object is an unknown (and
# probably damaged with respect to the module author's intents)
# state.
# This function will reload the module if it was already
# imported. See PyImport_ReloadModule() for the intended way to
# reload a module.
# If name points to a dotted name of the form package.module, any
# package structures not already created will still not be
# created.
long PyImport_GetMagicNumber()
# Return the magic number for Python bytecode files (a.k.a. .pyc
# and .pyo files). The magic number should be present in the first
# four bytes of the bytecode file, in little-endian byte order.
PyObject* PyImport_GetModuleDict()
# Return value: Borrowed reference.
# Return the dictionary used for the module administration
# (a.k.a. sys.modules). Note that this is a per-interpreter
# variable.
int PyImport_ImportFrozenModule(char *name)
# Load a frozen module named name. Return 1 for success, 0 if the
# module is not found, and -1 with an exception set if the
# initialization failed. To access the imported module on a
# successful load, use PyImport_ImportModule(). (Note the misnomer
# -- this function would reload the module if it was already
# imported.)
int PyImport_ExtendInittab(_inittab *newtab)
# Add a collection of modules to the table of built-in
# modules. The newtab array must end with a sentinel entry which
# contains NULL for the name field; failure to provide the
# sentinel value can result in a memory fault. Returns 0 on
# success or -1 if insufficient memory could be allocated to
# extend the internal table. In the event of failure, no modules
# are added to the internal table. This should be called before
# Py_Initialize().
#####################################################################
# 7.5.5 Module Objects
#####################################################################
# PyTypeObject PyModule_Type
# This instance of PyTypeObject represents the Python module
# type. This is exposed to Python programs as types.ModuleType.
bint PyModule_Check(object p)
# Return true if p is a module object, or a subtype of a module
# object.
bint PyModule_CheckExact(object p)
# Return true if p is a module object, but not a subtype of PyModule_Type.
object PyModule_New( char *name)
# Return value: New reference.
# Return a new module object with the __name__ attribute set to
# name. Only the module's __doc__ and __name__ attributes are
# filled in; the caller is responsible for providing a __file__
# attribute.
PyObject* PyModule_GetDict(object module)
# Return value: Borrowed reference.
# Return the dictionary object that implements module's namespace;
# this object is the same as the __dict__ attribute of the module
# object. This function never fails. It is recommended extensions
# use other PyModule_*() and PyObject_*() functions rather than
# directly manipulate a module's __dict__.
char* PyModule_GetName(object module)
# Return module's __name__ value. If the module does not provide
# one, or if it is not a string, SystemError is raised and NULL is
# returned.
char* PyModule_GetFilename(object module)
# Return the name of the file from which module was loaded using
# module's __file__ attribute. If this is not defined, or if it is
# not a string, raise SystemError and return NULL.
int PyModule_AddObject(object module, char *name, object value)
# Add an object to module as name. This is a convenience function
# which can be used from the module's initialization
# function. This steals a reference to value. Return -1 on error,
# 0 on success.
int PyModule_AddIntant(object module, char *name, long value)
# Add an integer ant to module as name. This convenience
# function can be used from the module's initialization
# function. Return -1 on error, 0 on success.
int PyModule_AddStringant(object module, char *name, char *value)
# Add a string constant to module as name. This convenience
# function can be used from the module's initialization
# function. The string value must be null-terminated. Return -1 on
# error, 0 on success.
This diff is collapsed.
This diff is collapsed.
cdef extern from "Python.h":
ctypedef void PyObject
#####################################################################
# 5.5 Parsing arguments and building values
#####################################################################
ctypedef struct va_list
int PyArg_ParseTuple(PyObject *args, char *format, ...)
int PyArg_VaParse(PyObject *args, char *format, va_list vargs)
int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, char *format, char *keywords[], ...)
int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, char *format, char *keywords[], va_list vargs)
int PyArg_Parse(PyObject *args, char *format, ...)
int PyArg_UnpackTuple(PyObject *args, char *name, Py_ssize_t min, Py_ssize_t max, ...)
cdef extern from "Python.h":
ctypedef void PyObject
ctypedef void PyTypeObject
ctypedef struct FILE
#####################################################################
# 3. Reference Counts
#####################################################################
# The macros in this section are used for managing reference counts of Python objects.
void Py_INCREF(object o)
# Increment the reference count for object o. The object must not
# be NULL; if you aren't sure that it isn't NULL, use
# Py_XINCREF().
void Py_XINCREF(object o)
# Increment the reference count for object o. The object may be NULL, in which case the macro has no effect.
void Py_DECREF(object o)
# Decrement the reference count for object o. The object must not
# be NULL; if you aren't sure that it isn't NULL, use
# Py_XDECREF(). If the reference count reaches zero, the object's
# type's deallocation function (which must not be NULL) is
# invoked.
# Warning: The deallocation function can cause arbitrary Python
# code to be invoked (e.g. when a class instance with a __del__()
# method is deallocated). While exceptions in such code are not
# propagated, the executed code has free access to all Python
# global variables. This means that any object that is reachable
# from a global variable should be in a consistent state before
# Py_DECREF() is invoked. For example, code to delete an object
# from a list should copy a reference to the deleted object in a
# temporary variable, update the list data structure, and then
# call Py_DECREF() for the temporary variable.
void Py_XDECREF(object o)
# Decrement the reference count for object o. The object may be
# NULL, in which case the macro has no effect; otherwise the
# effect is the same as for Py_DECREF(), and the same warning
# applies.
void Py_CLEAR(object o)
# Decrement the reference count for object o. The object may be
# NULL, in which case the macro has no effect; otherwise the
# effect is the same as for Py_DECREF(), except that the argument
# is also set to NULL. The warning for Py_DECREF() does not apply
# with respect to the object passed because the macro carefully
# uses a temporary variable and sets the argument to NULL before
# decrementing its reference count.
# It is a good idea to use this macro whenever decrementing the
# value of a variable that might be traversed during garbage
# collection.
############################################################################
# 6.3 Sequence Protocol
############################################################################
cdef extern from "Python.h":
ctypedef void PyObject
bint PySequence_Check(object o)
# Return 1 if the object provides sequence protocol, and 0
# otherwise. This function always succeeds.
Py_ssize_t PySequence_Size(object o)
# Returns the number of objects in sequence o on success, and -1
# on failure. For objects that do not provide sequence protocol,
# this is equivalent to the Python expression "len(o)".
Py_ssize_t PySequence_Length(object o)
# Alternate name for PySequence_Size().
object PySequence_Concat(object o1, object o2)
# Return value: New reference.
# Return the concatenation of o1 and o2 on success, and NULL on
# failure. This is the equivalent of the Python expression "o1 +
# o2".
object PySequence_Repeat(object o, Py_ssize_t count)
# Return value: New reference.
# Return the result of repeating sequence object o count times, or
# NULL on failure. This is the equivalent of the Python expression
# "o * count".
object PySequence_InPlaceConcat(object o1, object o2)
# Return value: New reference.
# Return the concatenation of o1 and o2 on success, and NULL on
# failure. The operation is done in-place when o1 supports
# it. This is the equivalent of the Python expression "o1 += o2".
object PySequence_InPlaceRepeat(object o, Py_ssize_t count)
# Return value: New reference.
# Return the result of repeating sequence object o count times, or
# NULL on failure. The operation is done in-place when o supports
# it. This is the equivalent of the Python expression "o *=
# count".
object PySequence_GetItem(object o, Py_ssize_t i)
# Return value: New reference.
# Return the ith element of o, or NULL on failure. This is the
# equivalent of the Python expression "o[i]".
object PySequence_GetSlice(object o, Py_ssize_t i1, Py_ssize_t i2)
# Return value: New reference.
# Return the slice of sequence object o between i1 and i2, or NULL
# on failure. This is the equivalent of the Python expression
# "o[i1:i2]".
int PySequence_SetItem(object o, Py_ssize_t i, object v)
# Assign object v to the ith element of o. Returns -1 on
# failure. This is the equivalent of the Python statement "o[i] =
# v". This function does not steal a reference to v.
int PySequence_DelItem(object o, Py_ssize_t i)
# Delete the ith element of object o. Returns -1 on failure. This
# is the equivalent of the Python statement "del o[i]".
int PySequence_SetSlice(object o, Py_ssize_t i1, Py_ssize_t i2, object v)
# Assign the sequence object v to the slice in sequence object o
# from i1 to i2. This is the equivalent of the Python statement
# "o[i1:i2] = v".
int PySequence_DelSlice(object o, Py_ssize_t i1, Py_ssize_t i2)
# Delete the slice in sequence object o from i1 to i2. Returns -1
# on failure. This is the equivalent of the Python statement "del
# o[i1:i2]".
int PySequence_Count(object o, object value)
# Return the number of occurrences of value in o, that is, return
# the number of keys for which o[key] == value. On failure, return
# -1. This is equivalent to the Python expression
# "o.count(value)".
int PySequence_Contains(object o, object value)
# Determine if o contains value. If an item in o is equal to
# value, return 1, otherwise return 0. On error, return -1. This
# is equivalent to the Python expression "value in o".
int PySequence_Index(object o, object value)
# Return the first index i for which o[i] == value. On error,
# return -1. This is equivalent to the Python expression
# "o.index(value)".
object PySequence_List(object o)
# Return value: New reference.
# Return a list object with the same contents as the arbitrary
# sequence o. The returned list is guaranteed to be new.
object PySequence_Tuple(object o)
# Return value: New reference.
# Return a tuple object with the same contents as the arbitrary
# sequence o or NULL on failure. If o is a tuple, a new reference
# will be returned, otherwise a tuple will be constructed with the
# appropriate contents. This is equivalent to the Python
# expression "tuple(o)".
object PySequence_Fast(object o, char *m)
# Return value: New reference.
# Returns the sequence o as a tuple, unless it is already a tuple
# or list, in which case o is returned. Use
# PySequence_Fast_GET_ITEM() to access the members of the
# result. Returns NULL on failure. If the object is not a
# sequence, raises TypeError with m as the message text.
PyObject* PySequence_Fast_GET_ITEM(object o, Py_ssize_t i)
# Return value: Borrowed reference.
# Return the ith element of o, assuming that o was returned by
# PySequence_Fast(), o is not NULL, and that i is within bounds.
PyObject** PySequence_Fast_ITEMS(object o)
# Return the underlying array of PyObject pointers. Assumes that o
# was returned by PySequence_Fast() and o is not NULL.
object PySequence_ITEM(object o, Py_ssize_t i)
# Return value: New reference.
# Return the ith element of o or NULL on failure. Macro form of
# PySequence_GetItem() but without checking that
# PySequence_Check(o) is true and without adjustment for negative
# indices.
int PySequence_Fast_GET_SIZE(object o)
# Returns the length of o, assuming that o was returned by
# PySequence_Fast() and that o is not NULL. The size can also be
# gotten by calling PySequence_Size() on o, but
# PySequence_Fast_GET_SIZE() is faster because it can assume o is
# a list or tuple.
cdef extern from "Python.h":
ctypedef void PyObject
############################################################################
# 7.5.14 Set Objects
############################################################################
# This section details the public API for set and frozenset
# objects. Any functionality not listed below is best accessed
# using the either the abstract object protocol (including
# PyObject_CallMethod(), PyObject_RichCompareBool(),
# PyObject_Hash(), PyObject_Repr(), PyObject_IsTrue(),
# PyObject_Print(), and PyObject_GetIter()) or the abstract number
# protocol (including PyNumber_Add(), PyNumber_Subtract(),
# PyNumber_Or(), PyNumber_Xor(), PyNumber_InPlaceAdd(),
# PyNumber_InPlaceSubtract(), PyNumber_InPlaceOr(), and
# PyNumber_InPlaceXor()).
# PySetObject
# This subtype of PyObject is used to hold the internal data for
# both set and frozenset objects. It is like a PyDictObject in
# that it is a fixed size for small sets (much like tuple storage)
# and will point to a separate, variable sized block of memory for
# medium and large sized sets (much like list storage). None of
# the fields of this structure should be considered public and are
# subject to change. All access should be done through the
# documented API rather than by manipulating the values in the
# structure.
# PyTypeObject PySet_Type
# This is an instance of PyTypeObject representing the Python set type.
# PyTypeObject PyFrozenSet_Type
# This is an instance of PyTypeObject representing the Python frozenset type.
# The following type check macros work on pointers to any Python
# object. Likewise, the constructor functions work with any
# iterable Python object.
bint PyAnySet_Check(object p)
# Return true if p is a set object, a frozenset object, or an
# instance of a subtype.
bint PyAnySet_CheckExact(object p)
# Return true if p is a set object or a frozenset object but not
# an instance of a subtype.
bint PyFrozenSet_CheckExact(object p)
# Return true if p is a frozenset object but not an instance of a subtype.
PySet_New(object iterable)
# Return value: New reference.
# Return a new set containing objects returned by the
# iterable. The iterable may be NULL to create a new empty
# set. Return the new set on success or NULL on failure. Raise
# TypeError if iterable is not actually iterable. The constructor
# is also useful for copying a set (c=set(s)).
PyFrozenSet_New(object iterable)
# Return value: New reference.
# Return a new frozenset containing objects returned by the
# iterable. The iterable may be NULL to create a new empty
# frozenset. Return the new set on success or NULL on
# failure. Raise TypeError if iterable is not actually iterable.
# The following functions and macros are available for instances of set or frozenset or instances of their subtypes.
int PySet_Size(object anyset)
# Return the length of a set or frozenset object. Equivalent to
# "len(anyset)". Raises a PyExc_SystemError if anyset is not a
# set, frozenset, or an instance of a subtype.
int PySet_GET_SIZE(object anyset)
# Macro form of PySet_Size() without error checking.
int PySet_Contains(object anyset, object key)
# Return 1 if found, 0 if not found, and -1 if an error is
# encountered. Unlike the Python __contains__() method, this
# function does not automatically convert unhashable sets into
# temporary frozensets. Raise a TypeError if the key is
# unhashable. Raise PyExc_SystemError if anyset is not a set,
# frozenset, or an instance of a subtype.
# The following functions are available for instances of set or
# its subtypes but not for instances of frozenset or its subtypes.
int PySet_Add(object set, object key)
# Add key to a set instance. Does not apply to frozenset
# instances. Return 0 on success or -1 on failure. Raise a
# TypeError if the key is unhashable. Raise a MemoryError if there
# is no room to grow. Raise a SystemError if set is an not an
# instance of set or its subtype.
int PySet_Discard(object set, object key)
# Return 1 if found and removed, 0 if not found (no action taken),
# and -1 if an error is encountered. Does not raise KeyError for
# missing keys. Raise a TypeError if the key is unhashable. Unlike
# the Python discard() method, this function does not
# automatically convert unhashable sets into temporary
# frozensets. Raise PyExc_SystemError if set is an not an instance
# of set or its subtype.
PySet_Pop(object set)
# Return value: New reference.
# Return a new reference to an arbitrary object in the set, and
# removes the object from the set. Return NULL on failure. Raise
# KeyError if the set is empty. Raise a SystemError if set is an
# not an instance of set or its subtype.
int PySet_Clear(object set)
# Empty an existing set of all elements.
cdef extern from "Python.h":
ctypedef void PyObject
ctypedef struct va_list
############################################################################
# 7.3.1 String Objects
############################################################################
# These functions raise TypeError when expecting a string
# parameter and are called with a non-string parameter.
# PyStringObject
# This subtype of PyObject represents a Python string object.
# PyTypeObject PyString_Type
# This instance of PyTypeObject represents the Python string type;
# it is the same object as str and types.StringType in the Python
# layer.
bint PyString_Check(object o)
# Return true if the object o is a string object or an instance of
# a subtype of the string type.
bint PyString_CheckExact(object o)
# Return true if the object o is a string object, but not an instance of a subtype of the string type.
object PyString_FromString(char *v)
# Return value: New reference.
# Return a new string object with the value v on success, and NULL
# on failure. The parameter v must not be NULL; it will not be
# checked.
object PyString_FromStringAndSize(char *v, Py_ssize_t len)
# Return value: New reference.
# Return a new string object with the value v and length len on
# success, and NULL on failure. If v is NULL, the contents of the
# string are uninitialized.
object PyString_FromFormat(char *format, ...)
# Return value: New reference.
# Take a C printf()-style format string and a variable number of
# arguments, calculate the size of the resulting Python string and
# return a string with the values formatted into it. The variable
# arguments must be C types and must correspond exactly to the
# format characters in the format string. The following format
# characters are allowed:
# Format Characters Type Comment
# %% n/a The literal % character.
# %c int A single character, represented as an C int.
# %d int Exactly equivalent to printf("%d").
# %u unsigned int Exactly equivalent to printf("%u").
# %ld long Exactly equivalent to printf("%ld").
# %lu unsigned long Exactly equivalent to printf("%lu").
# %zd Py_ssize_t Exactly equivalent to printf("%zd").
# %zu size_t Exactly equivalent to printf("%zu").
# %i int Exactly equivalent to printf("%i").
# %x int Exactly equivalent to printf("%x").
# %s char* A null-terminated C character array.
# %p void* The hex representation of a C pointer.
# Mostly equivalent to printf("%p") except that it is guaranteed to
# start with the literal 0x regardless of what the platform's printf
# yields.
# An unrecognized format character causes all the rest of the
# format string to be copied as-is to the result string, and any
# extra arguments discarded.
object PyString_FromFormatV(char *format, va_list vargs)
# Return value: New reference.
# Identical to PyString_FromFormat() except that it takes exactly two arguments.
Py_ssize_t PyString_Size(object string)
# Return the length of the string in string object string.
Py_ssize_t PyString_GET_SIZE(object string)
# Macro form of PyString_Size() but without error checking.
char* PyString_AsString(object string)
# Return a NUL-terminated representation of the contents of
# string. The pointer refers to the internal buffer of string, not
# a copy. The data must not be modified in any way, unless the
# string was just created using PyString_FromStringAndSize(NULL,
# size). It must not be deallocated. If string is a Unicode
# object, this function computes the default encoding of string
# and operates on that. If string is not a string object at all,
# PyString_AsString() returns NULL and raises TypeError.
char* PyString_AS_STRING(object string)
# Macro form of PyString_AsString() but without error
# checking. Only string objects are supported; no Unicode objects
# should be passed.
int PyString_AsStringAndSize(object obj, char **buffer, Py_ssize_t *length)
# Return a NULL-terminated representation of the contents of the
# object obj through the output variables buffer and length.
#
# The function accepts both string and Unicode objects as
# input. For Unicode objects it returns the default encoded
# version of the object. If length is NULL, the resulting buffer
# may not contain NUL characters; if it does, the function returns
# -1 and a TypeError is raised.
# The buffer refers to an internal string buffer of obj, not a
# copy. The data must not be modified in any way, unless the
# string was just created using PyString_FromStringAndSize(NULL,
# size). It must not be deallocated. If string is a Unicode
# object, this function computes the default encoding of string
# and operates on that. If string is not a string object at all,
# PyString_AsStringAndSize() returns -1 and raises TypeError.
void PyString_Concat(PyObject **string, object newpart)
# Create a new string object in *string containing the contents of
# newpart appended to string; the caller will own the new
# reference. The reference to the old value of string will be
# stolen. If the new string cannot be created, the old reference
# to string will still be discarded and the value of *string will
# be set to NULL; the appropriate exception will be set.
void PyString_ConcatAndDel(PyObject **string, object newpart)
# Create a new string object in *string containing the contents of
# newpart appended to string. This version decrements the
# reference count of newpart.
int _PyString_Resize(PyObject **string, Py_ssize_t newsize)
# A way to resize a string object even though it is
# ``immutable''. Only use this to build up a brand new string
# object; don't use this if the string may already be known in
# other parts of the code. It is an error to call this function if
# the refcount on the input string object is not one. Pass the
# address of an existing string object as an lvalue (it may be
# written into), and the new size desired. On success, *string
# holds the resized string object and 0 is returned; the address
# in *string may differ from its input value. If the reallocation
# fails, the original string object at *string is deallocated,
# *string is set to NULL, a memory exception is set, and -1 is
# returned.
object PyString_Format(object format, object args)
# Return value: New reference. Return a new string object from
# format and args. Analogous to format % args. The args argument
# must be a tuple.
void PyString_InternInPlace(PyObject **string)
# Intern the argument *string in place. The argument must be the
# address of a pointer variable pointing to a Python string
# object. If there is an existing interned string that is the same
# as *string, it sets *string to it (decrementing the reference
# count of the old string object and incrementing the reference
# count of the interned string object), otherwise it leaves
# *string alone and interns it (incrementing its reference
# count). (Clarification: even though there is a lot of talk about
# reference counts, think of this function as
# reference-count-neutral; you own the object after the call if
# and only if you owned it before the call.)
object PyString_InternFromString(char *v)
# Return value: New reference.
# A combination of PyString_FromString() and
# PyString_InternInPlace(), returning either a new string object
# that has been interned, or a new (``owned'') reference to an
# earlier interned string object with the same value.
object PyString_Decode(char *s, Py_ssize_t size, char *encoding, char *errors)
# Return value: New reference.
# Create an object by decoding size bytes of the encoded buffer s
# using the codec registered for encoding. encoding and errors
# have the same meaning as the parameters of the same name in the
# unicode() built-in function. The codec to be used is looked up
# using the Python codec registry. Return NULL if an exception was
# raised by the codec.
object PyString_AsDecodedObject(object str, char *encoding, char *errors)
# Return value: New reference.
# Decode a string object by passing it to the codec registered for
# encoding and return the result as Python object. encoding and
# errors have the same meaning as the parameters of the same name
# in the string encode() method. The codec to be used is looked up
# using the Python codec registry. Return NULL if an exception was
# raised by the codec.
object PyString_Encode(char *s, Py_ssize_t size, char *encoding, char *errors)
# Return value: New reference.
# Encode the char buffer of the given size by passing it to the
# codec registered for encoding and return a Python
# object. encoding and errors have the same meaning as the
# parameters of the same name in the string encode() method. The
# codec to be used is looked up using the Python codec
# registry. Return NULL if an exception was raised by the codec.
object PyString_AsEncodedObject(object str, char *encoding, char *errors)
# Return value: New reference.
# Encode a string object using the codec registered for encoding
# and return the result as Python object. encoding and errors have
# the same meaning as the parameters of the same name in the
# string encode() method. The codec to be used is looked up using
# the Python codec registry. Return NULL if an exception was
# raised by the codec.
cdef extern from "Python.h":
ctypedef void PyObject
############################################################################
# Tuples
############################################################################
bint PyTuple_Check(object p)
# Return true if p is a tuple object or an instance of a subtype
# of the tuple type.
bint PyTuple_CheckExact(object p)
# Return true if p is a tuple object, but not an instance of a subtype of the tuple type.
object PyTuple_New(Py_ssize_t len)
# Return value: New reference.
# Return a new tuple object of size len, or NULL on failure.
object PyTuple_Pack(Py_ssize_t n, ...)
# Return value: New reference.
# Return a new tuple object of size n, or NULL on failure. The
# tuple values are initialized to the subsequent n C arguments
# pointing to Python objects. "PyTuple_Pack(2, a, b)" is
# equivalent to "Py_BuildValue("(OO)", a, b)".
int PyTuple_Size(object p)
# Take a pointer to a tuple object, and return the size of that tuple.
int PyTuple_GET_SIZE(object p)
# Return the size of the tuple p, which must be non-NULL and point
# to a tuple; no error checking is performed.
PyObject* PyTuple_GetItem(object p, Py_ssize_t pos)
# Return value: Borrowed reference.
# Return the object at position pos in the tuple pointed to by
# p. If pos is out of bounds, return NULL and sets an IndexError
# exception.
PyObject* PyTuple_GET_ITEM(object p, Py_ssize_t pos)
# Return value: Borrowed reference.
# Like PyTuple_GetItem(), but does no checking of its arguments.
object PyTuple_GetSlice(object p, Py_ssize_t low, Py_ssize_t high)
# Return value: New reference.
# Take a slice of the tuple pointed to by p from low to high and return it as a new tuple.
int PyTuple_SetItem(object p, Py_ssize_t pos, object o)
# Insert a reference to object o at position pos of the tuple
# pointed to by p. Return 0 on success. Note: This function
# ``steals'' a reference to o.
void PyTuple_SET_ITEM(object p, Py_ssize_t pos, object o)
# Like PyTuple_SetItem(), but does no error checking, and should
# only be used to fill in brand new tuples. Note: This function
# ``steals'' a reference to o.
int _PyTuple_Resize(PyObject **p, Py_ssize_t newsize)
# Can be used to resize a tuple. newsize will be the new length of
# the tuple. Because tuples are supposed to be immutable, this
# should only be used if there is only one reference to the
# object. Do not use this if the tuple may already be known to
# some other part of the code. The tuple will always grow or
# shrink at the end. Think of this as destroying the old tuple and
# creating a new one, only more efficiently. Returns 0 on
# success. Client code should never assume that the resulting
# value of *p will be the same as before calling this function. If
# the object referenced by *p is replaced, the original *p is
# destroyed. On failure, returns -1 and sets *p to NULL, and
# raises MemoryError or SystemError.
cdef extern from "Python.h":
ctypedef void PyObject
ctypedef void PyTypeObject
# The C structure of the objects used to describe built-in types.
############################################################################
# 7.1.1 Type Objects
############################################################################
# PyObject* PyType_Type
# This is the type object for type objects; it is the same object
# as type and types.TypeType in the Python layer.
bint PyType_Check(object o)
# Return true if the object o is a type object, including
# instances of types derived from the standard type object. Return
# false in all other cases.
bint PyType_CheckExact(object o)
# Return true if the object o is a type object, but not a subtype
# of the standard type object. Return false in all other
# cases.
bint PyType_HasFeature(object o, int feature)
# Return true if the type object o sets the feature feature. Type
# features are denoted by single bit flags.
bint PyType_IS_GC(object o)
# Return true if the type object includes support for the cycle
# detector; this tests the type flag Py_TPFLAGS_HAVE_GC.
bint PyType_IsSubtype(object a, object b)
# Return true if a is a subtype of b.
object PyType_GenericAlloc(object type, Py_ssize_t nitems)
# Return value: New reference.
object PyType_GenericNew(object type, object args, object kwds)
# Return value: New reference.
bint PyType_Ready(object type)
# Finalize a type object. This should be called on all type
# objects to finish their initialization. This function is
# responsible for adding inherited slots from a type's base
# class. Return 0 on success, or return -1 and sets an exception
# on error.
cdef extern from "stdio.h":
ctypedef struct FILE
int printf(char *format, ...)
int fprintf(FILE *stream, char *format, ...)
int sprintf(char *str, char *format, ...)
FILE *fopen(char *path, char *mode)
int fclose(FILE *strea)
cdef FILE *stdout
int scanf(char *format, ...)
cdef extern from "stdlib.h":
ctypedef unsigned long size_t
void free(void *ptr)
void *malloc(size_t size)
void *realloc(void *ptr, size_t size)
size_t strlen(char *s)
char *strcpy(char *dest, char *src)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment