What is a PyObject in Python?

eric picture eric · Dec 29, 2014 · Viewed 16.4k times · Source

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

Answer

icktoofay picture icktoofay · Dec 29, 2014

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.