Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a PyObject in Python?

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

like image 458
eric Avatar asked Dec 29 '14 05:12

eric


People also ask

What does type () do in Python?

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.

What is type class in Python?

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.

What is Py_DECREF?

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).


2 Answers

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.

like image 170
icktoofay Avatar answered Sep 19 '22 13:09

icktoofay


A PyObject is in fact just a Python object at the C level. And since integers in Python are objects, they are also PyObjects. It doesn't matter whether it was written in Python or in C, it is a PyObject at the C level regardless.

like image 38
Ignacio Vazquez-Abrams Avatar answered Sep 18 '22 13:09

Ignacio Vazquez-Abrams