encukou / py3c

A Python 2/3 compatibility layer for C extensions
http://py3c.readthedocs.org
MIT License
59 stars 20 forks source link

Add support for PyFile_FromFile #44

Open javaprog opened 3 years ago

javaprog commented 3 years ago

In Python 2 there is only PyFile_FromFile, which accepts a file pointer, whereas in Python 3 there is only PyFile_FromFd, which accepts a file descriptor. To avoid changing legacy code and introducing special cases for both Python versions, I would like to suggest an implementation of PyFile_FromFile for Python 3 that simply forwards to the existing function: with the help of fileno() the file descriptor for a file pointer can be obtained.

encukou commented 3 years ago

To anyone looking for hints: In https://github.com/encukou/py3c/pull/45, implementing PyFile_FromFile in terms of PyFile_FromFd and fileno didn't work because it leaked FILE* structures.


Unfortunately, "file objects" in Python 3 are quite different than in Python 2. As the py3 docs say,

The [PyFile_* functions] are convenience C wrappers over these new APIs, and meant mostly for internal error reporting in the interpreter; third-party code is advised to access the io APIs instead.

Given that io is available on Python 2.6+, I'd rather encourage using that. It is what PyFile_FromFd does.