The functions in this chapter are specific to certain Python object types. Passing them an object of the wrong type is not a good idea; if you receive an object from a Python program and you are not sure that it has the right type, you must perform a type check first; for example, to check that an object is a dictionary, use PyDict_Check(). The chapter is structured like the “family tree” of Python object types.
Caveat
While the functions described in this chapter carefully check the type of the objects which are passed in, many of them do not check for NULL being passed instead of a valid object. Allowing NULL to be passed in can cause memory access violations and immediate termination of the interpreter.
This section describes Python type objects and the singleton object None.
The C structure of the objects used to describe built-in types.
This is the type object for type objects; it is the same object as type and types.TypeType in the Python layer.
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.
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.
Return true if the type object o sets the feature feature. Type features are denoted by single bit flags.
Return true if the type object includes support for the cycle detector; this tests the type flag Py_TPFLAGS_HAVE_GC.
Return true if a is a subtype of b.
XXX: Document.
XXX: Document.
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.
Note that the PyTypeObject for None is not directly exposed in the Python/C API. Since None is a singleton, testing for object identity (using == in C) is sufficient. There is no PyNone_Check() function for the same reason.
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.
The Python False object. This object has no methods. It needs to be treated just like any other object with respect to reference counts.
All integers are implemented as “long” integer objects of arbitrary size.
This instance of PyTypeObject represents the Python integer type. This is the same object as int.
Return true if its argument is a PyLongObject or a subtype of PyLongObject.
Return true if its argument is a PyLongObject, but not a subtype of PyLongObject.
Return a new PyLongObject object from v, or NULL on failure.
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. :-)
Return a new PyLongObject object from a C unsigned long, or NULL on failure.
Return a new PyLongObject object with a value of v, or NULL on failure.
Return a new PyLongObject object with a value of v, or NULL on failure.
Return a new PyLongObject object from a C long long, or NULL on failure.
Return a new PyLongObject object from a C unsigned long long, or NULL on failure.
Return a new PyLongObject object from the integer part of v, or NULL on failure.
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 '0o' or '0O', radix 8 will be used; if str starts with '0b' or '0B', radix 2 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.
Convert a sequence of Unicode digits to a Python integer value. The Unicode string is first encoded to a byte string using PyUnicode_EncodeDecimal() and then converted using PyLong_FromString().
Create a Python integer from the pointer p. The pointer value can be retrieved from the resulting value using PyLong_AsVoidPtr().
Return a C long representation of the contents of pylong. If pylong is greater than LONG_MAX, raise an OverflowError, and return -1. Convert non-long objects automatically to long first, and return -1 if that raises exceptions.
Return a C long representation of the contents of pylong. If pylong is greater than LONG_MAX, return -1 and set *overflow to 1 (for overflow) or -1 (for underflow). If an exception is set because of type errors, also return -1.
Return a C unsigned long representation of the contents of pylong. If pylong is greater than ULONG_MAX, an OverflowError is raised.
Return a Py_ssize_t representation of the contents of pylong. If pylong is greater than PY_SSIZE_T_MAX, an OverflowError is raised.
Return a size_t representation of the contents of pylong. If pylong is greater than the maximum value for a size_t, an OverflowError is raised.
Return a C long long from a Python integer. If pylong cannot be represented as a long long, an OverflowError will be raised.
Return a C unsigned long long from a Python 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.
Return a C unsigned long from a Python integer, without checking for overflow.
Return a C unsigned long long from a Python integer, without checking for overflow.
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.
Convert a Python 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().
Return the system’s idea of the largest integer it can handle (LONG_MAX, as defined in the system header files).
This instance of PyTypeObject represents the Python floating point type. This is the same object as float and types.FloatType.
Return true if its argument is a PyFloatObject or a subtype of PyFloatObject.
Return true if its argument is a PyFloatObject, but not a subtype of PyFloatObject.
Create a PyFloatObject object based on the string value in str, or NULL on failure.
Create a PyFloatObject object from v, or NULL on failure.
Return a C double representation of the contents of pyfloat. If pyfloat is not a Python floating point object but has a __float__() method, this method will first be called to convert pyfloat into a float.
Return a C double representation of the contents of pyfloat, but without error checking.
Return a PyDictObject object which contains information about the precision, minimum and maximum values of a float. It’s a thin wrapper around the header file float.h.
Return the maximum representable finite float DBL_MAX as C double.
Return the minimum normalized positive float DBL_MIN as C double.
Python’s complex number objects are implemented as two distinct types when viewed from the C API: one is the Python object exposed to Python programs, and the other is a C structure which represents the actual complex number value. The API provides functions for working with both.
Note that the functions which accept these structures as parameters and return them as results do so by value rather than dereferencing them through pointers. This is consistent throughout the API.
The C structure which corresponds to the value portion of a Python complex number object. Most of the functions for dealing with complex number objects use structures of this type as input or output values, as appropriate. It is defined as:
typedef struct {
double real;
double imag;
} Py_complex;
Return the sum of two complex numbers, using the C Py_complex representation.
Return the difference between two complex numbers, using the C Py_complex representation.
Return the negation of the complex number complex, using the C Py_complex representation.
Return the product of two complex numbers, using the C Py_complex representation.
Return the quotient of two complex numbers, using the C Py_complex representation.
Return the exponentiation of num by exp, using the C Py_complex representation.
This instance of PyTypeObject represents the Python complex number type. It is the same object as complex and types.ComplexType.
Return true if its argument is a PyComplexObject or a subtype of PyComplexObject.
Return true if its argument is a PyComplexObject, but not a subtype of PyComplexObject.
Create a new Python complex number object from a C Py_complex value.
Return a new PyComplexObject object from real and imag.
Return the Py_complex value of the complex number op.
If op is not a Python complex number object but has a __complex__() method, this method will first be called to convert op to a Python complex number object.
Generic operations on sequence objects were discussed in the previous chapter; this section deals with the specific kinds of sequence objects that are intrinsic to the Python language.
These functions raise TypeError when expecting a string parameter and are called with a non-string parameter.
This instance of PyTypeObject represents the Python string type; it is the same object as str and types.StringType in the Python layer. .
Return true if the object o is a string object or an instance of a subtype of the string type.
Return true if the object o is a string object, but not an instance of a subtype of the string type.
Return a new string object with a copy of the string v as value on success, and NULL on failure. The parameter v must not be NULL; it will not be checked.
Return a new string object with a copy of the string v as value and length len on success, and NULL on failure. If v is NULL, the contents of the string are uninitialized.
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.
Return a NUL-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.
These are the basic Unicode object types used for the Unicode implementation in Python:
Note that UCS2 and UCS4 Python builds are not binary compatible. Please keep this in mind when writing extensions or interfaces.
The following APIs are really C macros and can be used to do fast checks and to access internal read-only data of Unicode objects:
Unicode provides many different character properties. The most often needed ones are available through these macros which are mapped to C functions depending on the Python configuration.
These APIs can be used for fast direct character conversions:
To create Unicode objects and access their basic sequence properties, use these APIs:
Take a C printf()-style format string and a variable number of arguments, calculate the size of the resulting Python unicode 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. |
| %U | PyObject* | A unicode object. |
| %V | PyObject*, char * | A unicode object (which may be NULL) and a null-terminated C character array as a second parameter (which will be used, if the first parameter is NULL). |
| %S | PyObject* | The result of calling PyObject_Unicode(). |
| %R | PyObject* | The result of calling PyObject_Repr(). |
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.
Coerce an encoded object obj to an Unicode object and return a reference with incremented refcount.
String and other char buffer compatible objects are decoded according to the given encoding and using the error handling defined by errors. Both can be NULL to have the interface use the default values (see the next section for details).
All other objects, including Unicode objects, cause a TypeError to be set.
The API returns NULL if there was an error. The caller is responsible for decref’ing the returned objects.
If the platform supports wchar_t and provides a header file wchar.h, Python can interface directly to this type using the following functions. Support is optimized if Python’s own Py_UNICODE type is identical to the system’s wchar_t.
Python provides a set of builtin codecs which are written in C for speed. All of these codecs are directly usable via the following functions.
Many of the following APIs take two arguments encoding and errors. These parameters encoding and errors have the same semantics as the ones of the builtin unicode() Unicode object constructor.
Setting encoding to NULL causes the default encoding to be used which is ASCII. The file system calls should use Py_FileSystemDefaultEncoding as the encoding for file names. This variable should be treated as read-only: On some systems, it will be a pointer to a static string, on others, it will change at run-time (such as when the application invokes setlocale).
Error handling is set by errors which may also be set to NULL meaning to use the default handling defined for the codec. Default error handling for all builtin codecs is “strict” (ValueError is raised).
The codecs all use a similar interface. Only deviation from the following generic ones are documented for simplicity.
These are the generic codec APIs:
These are the UTF-8 codec APIs:
These are the UTF-32 codec APIs:
Decode length bytes from a UTF-32 encoded buffer string and return the corresponding Unicode object. errors (if non-NULL) defines the error handling. It defaults to “strict”.
If byteorder is non-NULL, the decoder starts decoding using the given byte order:
*byteorder == -1: little endian
*byteorder == 0: native order
*byteorder == 1: big endian
and then switches if the first four bytes of the input data are a byte order mark (BOM) and the specified byte order is native order. This BOM is not copied into the resulting Unicode string. After completion, *byteorder is set to the current byte order at the end of input data.
In a narrow build codepoints outside the BMP will be decoded as surrogate pairs.
If byteorder is NULL, the codec starts in native order mode.
Return NULL if an exception was raised by the codec.
Return a Python bytes object holding the UTF-32 encoded value of the Unicode data in s. If byteorder is not 0, output is written according to the following byte order:
byteorder == -1: little endian
byteorder == 0: native byte order (writes a BOM mark)
byteorder == 1: big endian
If byteorder is 0, the output string will always start with the Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is prepended.
If Py_UNICODE_WIDE is not defined, surrogate pairs will be output as a single codepoint.
Return NULL if an exception was raised by the codec.
These are the UTF-16 codec APIs:
Decode length bytes from a UTF-16 encoded buffer string and return the corresponding Unicode object. errors (if non-NULL) defines the error handling. It defaults to “strict”.
If byteorder is non-NULL, the decoder starts decoding using the given byte order:
*byteorder == -1: little endian
*byteorder == 0: native order
*byteorder == 1: big endian
and then switches if the first two bytes of the input data are a byte order mark (BOM) and the specified byte order is native order. This BOM is not copied into the resulting Unicode string. After completion, *byteorder is set to the current byte order at the end of input data.
If byteorder is NULL, the codec starts in native order mode.
Return NULL if an exception was raised by the codec.
Return a Python string object holding the UTF-16 encoded value of the Unicode data in s. If byteorder is not 0, output is written according to the following byte order:
byteorder == -1: little endian
byteorder == 0: native byte order (writes a BOM mark)
byteorder == 1: big endian
If byteorder is 0, the output string will always start with the Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is prepended.
If Py_UNICODE_WIDE is defined, a single Py_UNICODE value may get represented as a surrogate pair. If it is not defined, each Py_UNICODE values is interpreted as an UCS-2 character.
Return NULL if an exception was raised by the codec.
These are the “Unicode Escape” codec APIs:
These are the “Raw Unicode Escape” codec APIs:
These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode ordinals and only these are accepted by the codecs during encoding.
These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other codes generate errors.
These are the mapping codec APIs:
This codec is special in that it can be used to implement many different codecs (and this is in fact what was done to obtain most of the standard codecs included in the encodings package). The codec uses mapping to encode and decode characters.
Decoding mappings must map single string characters to single Unicode characters, integers (which are then interpreted as Unicode ordinals) or None (meaning “undefined mapping” and causing an error).
Encoding mappings must map single Unicode characters to single string characters, integers (which are then interpreted as Latin-1 ordinals) or None (meaning “undefined mapping” and causing an error).
The mapping objects provided must only support the __getitem__ mapping interface.
If a character lookup fails with a LookupError, the character is copied as-is meaning that its ordinal value will be interpreted as Unicode or Latin-1 ordinal resp. Because of this, mappings only need to contain those mappings which map characters to different code points.
The following codec API is special in that maps Unicode to Unicode.
Translate a Py_UNICODE buffer of the given length by applying a character mapping table to it and return the resulting Unicode object. Return NULL when an exception was raised by the codec.
The mapping table must map Unicode ordinal integers to Unicode ordinal integers or None (causing deletion of the character).
Mapping tables need only provide the __getitem__() interface; dictionaries and sequences work well. Unmapped character ordinals (ones which cause a LookupError) are left untouched and are copied as-is.
These are the MBCS codec APIs. They are currently only available on Windows and use the Win32 MBCS converters to implement the conversions. Note that MBCS (or DBCS) is a class of encodings, not just one. The target encoding is defined by the user settings on the machine running the codec.
The following APIs are capable of handling Unicode objects and strings on input (we refer to them as strings in the descriptions) and return Unicode objects or integers as appropriate.
They all return NULL or -1 if an exception occurs.
Translate a string by applying a character mapping table to it and return the resulting Unicode object.
The mapping table must map Unicode ordinal integers to Unicode ordinal integers or None (causing deletion of the character).
Mapping tables need only provide the __getitem__() interface; dictionaries and sequences work well. Unmapped character ordinals (ones which cause a LookupError) are left untouched and are copied as-is.
errors has the usual meaning for codecs. It may be NULL which indicates to use the default error handling.
Rich compare two unicode strings and return one of the following:
Note that Py_EQ and Py_NE comparisons can cause a UnicodeWarning in case the conversion of the arguments to Unicode fails with a UnicodeDecodeError.
Possible values for op are Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, and Py_LE.
Check whether element is contained in container and return true or false accordingly.
element has to coerce to a one element Unicode string. -1 is returned if there was an error.
Python objects implemented in C can export a group of functions called the “buffer interface.” These functions can be used by an object to expose its data in a raw, byte-oriented format. Clients of the object can use the buffer interface to access the object data directly, without needing to copy it first.
Two examples of objects that support the buffer interface are strings and arrays. The string object exposes the character contents in the buffer interface’s byte-oriented form. An array can also expose its contents, but it should be noted that array elements may be multi-byte values.
An example user of the buffer interface is the file object’s write() method. Any object that can export a series of bytes through the buffer interface can be written to a file. There are a number of format codes to PyArg_ParseTuple() that operate against an object’s buffer interface, returning data from the target object.
More information on the buffer interface is provided in the section Buffer Object Structures, under the description for PyBufferProcs.
A “buffer object” is defined in the bufferobject.h header (included by Python.h). These objects look very similar to string objects at the Python programming level: they support slicing, indexing, concatenation, and some other standard string operations. However, their data can come from one of two sources: from a block of memory, or from another object which exports the buffer interface.
Buffer objects are useful as a way to expose the data from another object’s buffer interface to the Python programmer. They can also be used as a zero-copy slicing mechanism. Using their ability to reference a block of memory, it is possible to expose any data to the Python programmer quite easily. The memory could be a large, constant array in a C extension, it could be a raw block of memory for manipulation before passing to an operating system library, or it could be used to pass around structured data in its native, in-memory format.
The instance of PyTypeObject which represents the Python buffer type; it is the same object as buffer and types.BufferType in the Python layer. .
This instance of PyTypeObject represents the Python tuple type; it is the same object as tuple and types.TupleType in the Python layer..
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.
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.
This instance of PyTypeObject represents the Python list type. This is the same object as list and types.ListType in the Python layer.
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().
Return the length of the list object in list; this is equivalent to len(list) on a list object.
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.
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.
This instance of PyTypeObject represents the Python dictionary type. This is exposed to Python programs as dict and types.DictType.
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.
Return the number of items in the dictionary. This is equivalent to len(p) on a dictionary.
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:
PyObject *key, *value;
Py_ssize_t pos = 0;
.. cnid:: 175
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:
PyObject *key, *value;
Py_ssize_t pos = 0;
.. cnid:: 177
while (PyDict_Next(self->dict, &pos, &key, &value)) {
int i = PyInt_AS_LONG(value) + 1;
PyObject *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);
}
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
Python’s built-in file objects are implemented entirely on the FILE* support from the C standard library. This is an implementation detail and may change in future releases of Python.
This instance of PyTypeObject represents the Python file type. This is exposed to Python programs as file and types.FileType.
Create a new PyFileObject from the file descriptor of an already opened file fd. The arguments name, encoding and newline can be NULL to use the defaults; buffering can be -1 to use the default. Return NULL on failure.
Caveat
Take care when you are mixing streams and descriptors! For more information, see the GNU C Library docs.
Equivalent to p.readline([n]), this function reads one line from the object p. p may be a file object or any object with a readline() method. If n is 0, exactly one line is read, regardless of the length of the line. If n is greater than 0, no more than n bytes will be read from the file; a partial line can be returned. In both cases, an empty string is returned if the end of the file is reached immediately. If n is less than 0, however, one line is read regardless of length, but EOFError is raised if the end of the file is reached immediately.
Available on systems with setvbuf() only. This should only be called immediately after file object creation.
This function exists for internal use by the interpreter. Set the softspace attribute of p to newflag and return the previous value. p does not have to be a file object for this function to work properly; any object is supported (thought its only interesting if the softspace attribute can be set). This function clears any errors, and will return 0 as the previous value if the attribute either does not exist or if there were errors in retrieving it. There is no way to detect errors from this function, but doing so should not be needed.
There are a few functions specific to Python functions.
This is an instance of PyTypeObject and represents the Python function type. It is exposed to Python programmers as types.FunctionType.
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.
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.
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.
Methods are bound function objects. Methods are always bound to an instance of an user-defined class. Unbound methods (methods bound to a class object) are no longer available.
This instance of PyTypeObject represents the Python method type. This is exposed to Python programs as types.MethodType.
There are only a few functions special to module objects.
This instance of PyTypeObject represents the Python module type. This is exposed to Python programs as types.ModuleType.
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.
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__.
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.
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.
Python provides two general-purpose iterator objects. The first, a sequence iterator, works with an arbitrary sequence supporting the __getitem__() method. The second works with a callable object and a sentinel value, calling the callable for each item in the sequence, and ending the iteration when the sentinel value is returned.
“Descriptors” are objects that describe some attribute of an object. They are found in the dictionary of type objects.
The type object for slice objects. This is the same as slice and types.SliceType.
Retrieve the start, stop and step indices from the slice object slice, assuming a sequence of length length. Treats indices greater than length as errors.
Returns 0 on success and -1 on error with no exception set (unless one of the indices was not None and failed to be converted to an integer, in which case -1 is returned with an exception set).
You probably do not want to use this function. If you want to use slice objects in versions of Python prior to 2.3, you would probably do well to incorporate the source of PySlice_GetIndicesEx(), suitably renamed, in the source of your extension.
Usable replacement for PySlice_GetIndices(). Retrieve the start, stop, and step indices from the slice object slice assuming a sequence of length length, and store the length of the slice in slicelength. Out of bounds indices are clipped in a manner consistent with the handling of normal slices.
Returns 0 on success and -1 on error with exception set.
Python supports weak references as first-class objects. There are two specific object types which directly implement weak references. The first is a simple reference object, and the second acts as a proxy for the original object as much as it can.
Refer to Extending and Embedding the Python Interpreter, section 1.12, “Providing a C API for an Extension Module,” for more information on using these objects.
“Cell” objects are used to implement variables referenced by multiple scopes. For each such variable, a cell object is created to store the value; the local variables of each stack frame that references the value contains a reference to the cells from outer scopes which also use that variable. When the value is accessed, the value contained in the cell is used instead of the cell object itself. This de-referencing of the cell object requires support from the generated byte-code; these are not automatically de-referenced when accessed. Cell objects are not likely to be useful elsewhere.
Generator objects are what Python uses to implement generator iterators. They are normally created by iterating over a function that yields values, rather than explicitly calling PyGen_New().
Various date and time objects are supplied by the datetime module. Before using any of these functions, the header file datetime.h must be included in your source (note that this is not included by Python.h), and the macro PyDateTime_IMPORT() must be invoked. The macro puts a pointer to a C structure into a static variable, PyDateTimeAPI, that is used by the following macros.
Type-check macros:
Macros to create objects:
Macros to extract fields from date objects. The argument must be an instance of PyDateTime_Date, including subclasses (such as PyDateTime_DateTime). The argument must not be NULL, and the type is not checked:
Macros to extract fields from datetime objects. The argument must be an instance of PyDateTime_DateTime, including subclasses. The argument must not be NULL, and the type is not checked:
Macros to extract fields from time objects. The argument must be an instance of PyDateTime_Time, including subclasses. The argument must not be NULL, and the type is not checked:
Macros for the convenience of modules implementing the DB API:
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_And(), PyNumber_Subtract(), PyNumber_Or(), PyNumber_Xor(), PyNumber_InPlaceAnd(), PyNumber_InPlaceSubtract(), PyNumber_InPlaceOr(), and PyNumber_InPlaceXor()).
The following type check macros work on pointers to any Python object. Likewise, the constructor functions work with any iterable Python object.
The following functions and macros are available for instances of set or frozenset or instances of their subtypes.
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.
The following functions are available for instances of set or its subtypes but not for instances of frozenset or its subtypes.
关于本评注系统
本站使用上下文关联的评注系统来收集反馈信息。不同于一般对整章做评注的做法, 我们允许你对每一个独立的“文本块”做评注。一个“文本块”看起来是这样的:
一个“文本块”是一个段落,一个列表项,一段代码,或者其他一小段内容。 你选中它会高亮度显示:
要对文本块做评注,你只需要点击它旁边的标识块:
我们会仔细阅读每个评论,如果可能的话我们也会把评注考虑到未来的版本中去:
如果你愿意你的评注被采用,请确保留下你的全名 (注意不是昵称或简称)
Many, many thanks to Jack Slocum; the inspiration and much of the code for the comment system comes from Jack's blog, and this site couldn't have been built without his wonderful
YAHOO.extlibrary. Thanks also to Yahoo for YUI itself.