Short version
I recently came across some Python code in which the return type for a function was specified as PyObject
in the documentation. What is a PyObject
?
Detailed version
I am not a C/C++ programmer, but when I ran into PyObject
in the documentation linked above, Google taught me that PyObject
is a Python object as defined using the Python/C API. Specifically, the API documentation defines PyObject as follows:
All object types are extensions of this type. This is a type which contains the information Python needs to treat a pointer to an object as an object. In a normal “release” build, it contains only the object’s reference count and a pointer to the corresponding type object. It corresponds to the fields defined by the expansion of the PyObject_HEAD macro.
Frankly, I don't fully understand this, or whether it answers my basic question, but it doesn't make me think it is obviously wrong to just think of a PyObject
as a Python object, full stop. On the other hand, perhaps to technically count as a PyObject
the type must have been created as an extension to standard Python using the Python/C API. For instance, is an integer a PyObject
?
Potentially relevant links
http://docs.scipy.org/doc/numpy/reference/c-api.types-and-structures.html
Python has a lot of built-in functions. The type() function is used to get the type of an object. When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object.
type is a metaclass, of which classes are instances. Just as an ordinary object is an instance of a class, any new-style class in Python, and thus any class in Python 3, is an instance of the type metaclass. In the above case: x is an instance of class Foo . Foo is an instance of the type metaclass.
Py_DECREF decreases the ref count from 1 to 0; as it finds the ref count is 0, it calls the appropriate functions to free the memory (Noddy_dealloc in this case.) If a python C api function returns NULL, something has gone wrong; usually an exception is set (saved in a global variable).
Every value you can touch in Python is a PyObject
in C. That includes lists, dictionaries, sockets, files, integers, strings, functions, classes, you name it. If you can touch it in Python, it’s a PyObject
in C.
A PyObject
is in fact just a Python object at the C level. And since integers in Python are objects, they are also PyObject
s. It doesn't matter whether it was written in Python or in C, it is a PyObject
at the C level regardless.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With