What do I need to do:
Given the binary, decode it in several ways by providing the TextIOBase API. Ideally, these subsequent files can be transferred without my need to clearly track their lifespan.
Unfortunately, packaging BufferedReader will cause the reader to close when TextIOWrapper goes beyond.
Here is a simple demonstration of this:
In [1]: import io In [2]: def mangle(x): ...: io.TextIOWrapper(x)
I can fix this in Python 3 by overriding __del__ (this is a reasonable solution for my use case, since I have full control over the decoding process, I just need to expose a very uniform API at the end):
In [1]: import io In [2]: class MyTextIOWrapper(io.TextIOWrapper): ...: def __del__(self): ...: print("I've been GC'ed") ...: In [3]: def mangle2(x): ...: MyTextIOWrapper(x) ...: In [4]: f2 = io.open('example', mode='rb') In [5]: f2.closed Out[5]: False In [6]: mangle2(f2) I've been GC'ed In [7]: f2.closed Out[7]: False
However, this does not work in Python 2:
In [7]: class MyTextIOWrapper(io.TextIOWrapper): ...: def __del__(self): ...: print("I've been GC'ed") ...: In [8]: def mangle2(x): ...: MyTextIOWrapper(x) ...: In [9]: f2 = io.open('example', mode='rb') In [10]: f2.closed Out[10]: False In [11]: mangle2(f2) I've been GC'ed In [12]: f2.closed Out[12]: True
I spent a bit of time looking at the Python source code and it looks surprisingly similar between 2.7 and 3.4, so I donβt understand why __del__ inherited from IOBase is not overridden in Python 2 (or even visible in dir ), but it still seems accomplished. Python 3 works exactly as expected.
Is there anything I can do?
ebolyen
source share