Reputation: 4718
I wrote some code in Python 2.7.2 and now I may need to switch to 3.4.3, but my code breaks (simply print
statements right now, but who knows what else). Is it possible to write the syntax in such a way that it will be compliant with both 2.7.2 and 3.4.3?
I am just starting out with Python and don't want to build habits with one flavor and then have to relearn things with another version later.
Upvotes: 1
Views: 233
Reputation: 738
There are already some great answers above. A quick fix for your print problems would be to make use of the future module which backports some Python 3 features to Python 2.
I'd recommend as a minimum writing you're Python 2.7 code with the new print function. To do this import the new print function from future. i.e.
from __future__ import print_function
You will now get syntax errors in Python 2 using print as:
print x
and will now have to do:
print(x)
Other solutions like 2to3 and six exist, but these might be a bit complicated at the moment, especially as you are learning Python.
Upvotes: 0
Reputation: 25181
Yes, Python code can be compatible with both Python 2 and 3.
There are 3 options how to do it:
keep the source code itself compatible with both Python 2 and 3; this is the most used way
use separate code for Python 2 and 3; generally not very useful, but maybe acceptable for some low-level code. For example CherryPy wsgiserver (notice the files wsgiserver2.py
and wsgiserver3.py
).
write code in either Python 2 or Python 3 and use automatic tool like 2to3 or 3to2 for translation to the other version.
When Python 3 was first released the 2to3 way was the preferred one. You can find this in What’s New In Python 3.0: "It is not recommended to try to write source code that runs unchanged under both Python 2.6 and 3.0." But times have changed since then. Some things were introduced that made writing code for both Python 2 and 3 much easier - for example the u""
syntax in Python 3.3. Also the tool 3to2 did not get much updates since 2010...
When writing code that works unchanged on both Python 2 and 3 some compatibility code with few simple if
s may be needed; look for example at flask/_compat.py. If this isn't sufficient then use six.
Some resources how to write code working on both Python 2 and 3:
http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/
http://python-future.org/compatible_idioms.html#essential-syntax-differences
The Python 2/3 problem applies mostly for libraries, shared code and Python 2 projects that are being upgraded to Python 3. If you are starting a project that is not a library then just go with Python 3 if possible.
Upvotes: 0
Reputation: 745
Yes, but depending on your code. You have lot of options:
from __future__ import ...
(making your code work with Python 2 & 3 - see e.g. this and this)modernize
six
Upvotes: 1