I’m working on some code that should run under both Python 2.7.x and Python 3.3+ unchanged, and uses Unicode data text file I/O.
So which is better—and why?
Variant 1:
import io
encoding = 'utf-8'
with io.open('Unicode.txt', 'w', encoding=encoding) as f:
…
with io.open('Unicode.txt', 'r', encoding=encoding) as f:
…
Variant 2:
from io import open
encoding = 'utf-8'
with open('Unicode.txt', 'w', encoding=encoding) as f:
…
with open('Unicode.txt', 'r', encoding=encoding) as f:
…
Personally, I’d tend to use Variant 2, because the code should be as Python-3-ish as possible, just providing backport stubs for Python 2.7.x. It also looks cleaner and I wouldn’t have to change existing code much. Also I think maybe I could save a little by not importing the whole io module.