PyObject
A PyObject
is a data structure used by CPython to store data objects in the memory. Everything in python is an object.
PyObject structure
CPython code has PyObject
which is a grand object. It stores following information:
- Reference Count: Total number of references for the actual data object.
- Pointer to the actual data object.
struct {
ob_refcnt,
ob_type
}
Reference count is used in freeing memory used by unused data objects. If reference counts becomes 0
, the memory is freed.
In multithreading applications, multiple threads may try to access the same object which can cause inconsistencies in data and eventually program crash. To stop this, python has gil which locks the interpreter for a thread and other threads wait for the lock to get released.