Changes between Initial Version and Version 1 of SocketFileAdapter

Oct 5, 2014, 3:13:57 PM (7 years ago)

Info page on socket file adapter


  • SocketFileAdapter

    v1 v1  
     1= Socket file adapter for Python 2 / 3 compatiblity =
     3== Motivation ==
     5To make ftputil usable for Python 3, I decided to use `io.TextIOWrapper` to add text encoding/decoding capabilities to file objects returned from `socket.makefile`.
     7In Python 3, `socket.makefile` has arguments to encode/decode on the fly, so `io.TextIOWrapper` isn't needed. Not so in Python 2. My idea was to use `socket.makefile` to create a binary file object on Python 2 and 3 and wrap this object with `io.TextIOWrapper`. Unfortunately, the file object returned from `socket.makefile` in Python 2 can't be wrapped directly. (To use `io.TextIOWrapper`, the `write` method of the wrapped file needs to return the number of written bytes, but the file object from `socket.makefile` in Python 2 returns `None`.)
     9== Solution ==
     11Hence I wrote an adapter to make the `socket.makefile` return value in Python 2 usable with `io.TextIOWrapper`. The adapter can be used like this:
     14# First create a socket file for binary I/O.
     15fobj = socket_.makefile("rb")  # or mode "wb"
     16# Adapt the interface of this object if on Python 2
     17if PYTHON_VERSION == 2:
     18    fobj = BufferedIOAdapter(fobj, is_readable=True)  # or `is_writable=True`
     19# If a text file (i. e. unicode I/O) is requested ...
     20fobj = io.TextIOWrapper(fobj, encoding=...)
     23== Download ==
     25This is the adapter module: [browser:ftputil/ formatted with syntax highlighting] , '''[export:/ftputil/ actual module file]'''.
     27Here's an [browser:ftputil/ usage example] in `ftputil.file.FTPFile._open`.