5

In python's source code, there are some macro definitions like this:

#define PyObject_HEAD    \
    int ob_refcnt;       \
    struct _typeobject *ob_type;


#define PyObject_VAR_HEAD  \
    PyObject_HEAD          \
    int ob_size; 


typedef struct _object {  
    PyObject_HEAD  
} PyObject;    

typedef struct _object {  
    PyObject_HEAD   
    long ob_ival;   
} PyIntObject;   

typedef struct {   
    PyObject_VAR_HEAD   
} PyVarObject;   

The question is, why PyObject* can point to each object(such as PyIntObject, PyVarObject) in python?

2
  • 1
    Are there some backslashes missing in the macro definitions? Commented Jul 31, 2012 at 9:20
  • Does it look correct now after I edited it? Commented Jul 31, 2012 at 11:04

2 Answers 2

12

Each struct for the different types of Python object has an instance of PyObject_HEAD as its first member (or the first member of its first member, and so on).

This member sub-object is guaranteed to be located at the same address as the full object.

The PyObject_HEAD* points at that member sub-object, but could be cast to the full type once ob_type has been inspected to work out what the full type is.

This trick isn't unique to CPython -- it's often used to implement a limited kind of inheritance in C. Basically you model the "is a X" relationship by "has a X at the start of".

Sign up to request clarification or add additional context in comments.

1 Comment

In this, it mentioned Py_REFCNT, Py_TYPE and Py_SIZE macros, but no #define's like Py_REFCNT(x) (x->ob_type). Can someone show their source code or the link to it?
2

Because PyObject_HEAD is ALWAYS the first struct member not affected by the concrete underlying type. The pointer will ofcourse get casted.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.