Changes between Initial Version and Version 1 of SocketFileAdapter


Ignore:
Timestamp:
Oct 5, 2014, 3:13:57 PM (7 years ago)
Author:
schwa
Comment:

Info page on socket file adapter

Legend:

Unmodified
Added
Removed
Modified
  • SocketFileAdapter

    v1 v1  
     1= Socket file adapter for Python 2 / 3 compatiblity =
     2
     3== Motivation ==
     4
     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`.
     6
     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`.)
     8
     9== Solution ==
     10
     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:
     12
     13{{{
     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=...)
     21}}}
     22
     23== Download ==
     24
     25This is the adapter module: [browser:ftputil/socket_file_adapter.py formatted with syntax highlighting] , '''[export:/ftputil/socket_file_adapter.py actual module file]'''.
     26
     27Here's an [browser:ftputil/file.py#L103 usage example] in `ftputil.file.FTPFile._open`.