FILE object in Python3.0 extension modules

Gabriel Genellina gagsl-py2 at
Sat May 30 03:41:03 CEST 2009

En Fri, 29 May 2009 06:52:15 -0300, Joachim Dahl <dahl.joachim at>  

> In Python2.x, I used PyFile_Check(obj) to check if a parameter was a
> file object.
> Now, in Python3.0 the same object (obtained as open('file.bin','wb'))
> is an
> io.BufferedWriter object.
> How do I perform type checking for such an object in the extension
> module,

I don't know which is the preferred way to check for a file object in 3.x  
- I hope someone can answer this more precisely. In principle, a file  
inherits from io.IOBase, but this class is defined in and probably  
isn't intended to be used in C code. Other alternatives are _io._IOBase,  
PyIOBase_Type, and io.FileIO/_io.FileIO

> and how do I extract a FILE * object from it?  I browsed the C API
> documentation,  but
> couldn't find an answer.

I'd use PyObject_AsFileDescriptor

(Notice that the documentation is outdated; the PyFileObject type does not  
exist anymore, and a file isn't a wrapper around a FILE struct either)

> The purpose is to dump the contents of a Python extension type to disk
> as
> binary data using C's fwrite() function.

 From the above, I'd use write() with the file descriptor obtained from  

Gabriel Genellina

More information about the Python-list mailing list