simple(?) Python C module question

Mark Crispin nospam at
Thu Nov 18 00:18:44 CET 2010

This is something that ought to be simple, but going through the 
documentation hasn't come up with the answer.  Hopefully someone can 
answer it faster than I can figure it out from the documentation.

I am using Python 2.6 for a project.  I do not have a choice in the 
matter, so telling me to use Python 3.1 is not helpful.  [I already wasted 
a while learning that Python 2.x and Python 3.x are very different, and 
documentation for the one is lies for the other........]

I know relatively little about Python, but am experienced in other OO 
languages.  The OO jargon I'll use in this question is as is used in 
SmallTalk or perhaps Objective-C (just in case Python uses other jargon).

I have a Python module written in C that interfaces with an external C 
library.  Basically, the project is to make it possible to use that 
library from Python scripts.  If you know who I am, you can guess which 
library.  :)

I have gotten as far as writing the module, and I can call methods in the 
module that call the library and do the intended thing.  So far, so good.

However, I now need to write a method that creates what the library calls 
a "stream", and I need method calls to work on that stream.

The obvious way to do this in any other OO language is to have an object 
that holds the stream from the library in an instance variable (which 
actually will be constant for that object instance), and has various 
object methods for operating on that stream.

I assume that the object methods are defined by a PyMethodDef table, just 
as they are for the module.  But how do I:
  [1] define the object
  [2] create an instance of the object with the stream and methods
  [3] hook the object's destruction to a library stream-close function

Python does NOT need to look at the stream in any way.  Ideally, the 
object is just a blob that only has method calls.

This ought to be simple, and not even require me to know much Python since 
basically the task is just this module and a few very basic Python scripts 
to use it.  Other people will be writing the real scripts.

Of course, I could just have the open method return the stream pointer as 
a big int, and have module methods that take the stream pointer as their 
first argument, just as in C code.  If I did that, the project would have 
been done by now.  But the result wouldn't be very OO or Pythonish; and 
more to the point other people will have to use it.  I hate when people 
inflict quick, dirty, stupid, ugly, lazy programmer abominations on me; 
and so I feel obligated to do it right rather than inflict an abomination 
on others...  :)

Thanks in advance for any pointers and/or help.

-- Mark --
Democracy is two wolves and a sheep deciding what to eat for lunch.
Liberty is a well-armed sheep contesting the vote.

More information about the Python-list mailing list