[CentralOH] New Types

Jeff Rush jeff at taupro.com
Thu Dec 13 09:07:05 CET 2007


David Car wrote:
> 
> I have a question about new types in Python.  Just finished reading up and 
> trying a few things out, but I'm a little confused about one thing.  When 
> declaring a new type, we basically have two new structures.  One is the per 
> instance structure (your PyObject structure), which is basically an expansion 
> of the PyObject structure.  At the beginning of that structure is the macro 
> declaration of PyObject_HEAD which contains the reference counter and a 
> pointer to the new type which is a structure of _typeobject.  Then for your 
> new type (i.e. your _typeobject structure) there is a place holder for the 
> size of your per instance PyObject structure along with all the necessary 
> function pointers your new type will support.

> My question is this:

> Where and when does the pointer in your per instance PyObject
> structure get set?  How does the interpreter know that your
> PyObject structure is related to your PyTypeObject structure?
> Since your PyObject structure naming convention is not tied
> to your PyTypeObject name, how are the two associated?

The connection and allocation occurs in the __new__ class method, which in
your code looks like:  (much detail omitted for readability)

typedef struct { /* instance structure */
  PyObject_HEAD;
  char *cardname;
} alsapcm_t;

static PyTypeObject ALSAPCMType; /* type structure */

alsapcm_new(...)
{
  /* allocates and initializes an instance */
  alsapcm_t *self = PyObject_New(alsapcm_t, &ALSAPCMType);
  return self;
}

There are some good comments in the file:

    /usr/include/python2.4/objimpl.h


> I see how
> your type is statically instantiated in the initialization, but I don't see 
> where your per instance PyObject is related to it?  Is it simply that the two 
> structures co-exist in the same module?

No magic.

BTW, if you are interested in the C aspects of Python like this one, you ought
to check out the mailing list "CAPI-SIG", at:

    http://mail.python.org/mailman/listinfo/capi-sig

It was created to keep C discussions off of the comp.lang.python list where
many folks only know Python anyway.

Your question re linking instance and type is a very good one though.

-Jeff (Dallas Pythoneer, but helping out where I can)


More information about the CentralOH mailing list