That’s a nice addition, @alveera.khn! And to build on that, I’ve worked with python textiowrapper quite a bit, especially when handling BytesIO streams. If you know you’re always working with BytesIO, you can simplify things quite a bit. Here’s a solution that ensures compatibility for both Python 2 and 3:
import io
import sys
def wrap_stream(binary_stream):
if sys.version_info[0] >= 3:
# Python 3: Directly wrap with python textiowrapper
return io.TextIOWrapper(binary_stream, encoding='utf-8')
else:
# Python 2: Wrap using io.BytesIO with utf-8 encoding
return io.TextIOWrapper(binary_stream, encoding='utf-8')
This assumes your binary_stream is already an instance of BytesIO, and it should work across both Python versions. The key here is that you’re still using TextIOWrapper in Python 3, and the fallback is just a TextIOWrapper on the Python 2 side—since Python 2 doesn’t have the exact equivalent of TextIOWrapper, it’s a way of ensuring consistent behavior regardless of the version you’re using.