[Tutor] trouble with stringio function in python 3.2
Chris Warrick
kwpolska at gmail.com
Mon May 4 09:46:22 CEST 2015
On Mon, May 4, 2015 at 7:03 AM, anupama srinivas murthy
<anupama.2312.bmsit at gmail.com> wrote:
> Hello,
>
> My python code needs to run on versions 2.7 to 3.4. To use stringio
> function as appropriate, the code i use is;
>
> if sys.version < '3':
A better comparison to use would be
if sys.version_info[0] == 2:
It’s the standard idiom, which compares 2 == 2 instead of '2.7.9 (more
garbage here)' < '3'.
> dictionary = io.StringIO(u"""\n""".join(english_words))
> else:
> dictionary = io.StringIO("""\n""".join(english_words))
>
> The code runs fine on all versions mentioned above except for 3.2 where i
> get the error:
> dictionary = io.StringIO(u"""\n""".join(english_words))
> ^
> SyntaxError: invalid syntax
>
> How can I solve the issue?
The best solution is not supporting Python 3.2, especially considering
that Python 3.3.0 was released in September 2012 (and the latest
version is 3.4.3).
Python 3.0–3.2 do not support the u'' notation for Unicode strings, it
was restored in Python 3.3 to make it easier to write code compatible
with 2.x and 3.x (just like you are trying to do here!) Python has to
read in and parse all the code, and it encounters a strange u'' thing
it does not recognize. Thus, it fails with a SyntaxError.
Many Python projects out there don’t support 3.2, and this was one of
the reasons.
If you REALLY have to support it (why?), there are two solutions. The
first one is to use '\n'.decode('utf-8') instead of u'\n' for Python
2.7, which will not trigger a compile error (it does not matter that
there is no str.decode in Python 3, the syntax makes sense even if it
cannot be executed). The second one is to use (at the top of your
file)
from __future__ import unicode_literals
This will make Python 2.7 think '\n' is a Unicode string, and Python
3.x will ignore this line — in that case, you can even drop the
if/else and just use the same dictionary assignment for both Pythons.
Just be warned that it applies to the entire file and can lead to
problems.
PS. There is no reason to use """multi-line strings""" in this case,
regular "strings" will do it equally well and are more readable.
--
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
More information about the Tutor
mailing list