Reputation: 61
I am making code that works on both Python 2 and Python 3. But there was no problem in theory, but there was a Python problem.
Now I'm build and use both Python 2.7.5 and Python 3.7.4.
This is part of my code
ex)
if sys.version_info < (3,):
print(keys),;
print(values)
else:
print(keys,'/ ', end='')
print(values)
This code that checks Python version with sys.version, corresponding 'if' will be working.
But, of course there is a syntax error. Python 2 does not support [end=''].
In my opinion... Even if you actually ignore it and act on it, there's no problem code. I tried 'Try-except', but syntax errors were not ignored.
How can both Python2 and Python3 not change lines while weaving compatible codes?
Upvotes: 1
Views: 1085
Reputation: 769
Import the package print_function
and try
from __future__ import print_function
Upvotes: 4
Reputation: 155506
In this particular case, just get the Python 3 print
function in both Python 2 and Python 3 by adding:
from __future__ import print_function
to the very top of your file, then only use the Python 3 syntax.
As for avoiding the SyntaxError
from actually incompatible constructs that can't be fixed with a __future__
import, the only solutions are putting the incompatible code in separate modules (a public module can do version testing to import the implementations from the private module appropriate to the Python version), or eval
ing a string containing the code for the appropriate version (exec
won't typically work, because it also changed from keyword statement to built-in function in the transition; eval
+compile
is the same in both though).
There is no way to just "turn off syntax checking", because invalid syntax definitionally means the parser has encountered an unrecoverable error; you don't want it to try to stumble onwards, guessing at what everything else means in the context of the garbage state it was left in.
Upvotes: 2