python-future
is the missing compatibility layer between Python 2 andPython 3. It allows you to use a single, clean Python 3.x-compatiblecodebase to support both Python 2 and Python 3 with minimal overhead.Easy data transform 1 1 00. Typing.AsyncContextManager was added to Python 3.6.2. The zipfile module accepts a path-like object since Python 3.6.2. Loop.createfuture was added to Python 3.5.2 in the asyncio module. No backward compatibility code is needed for these kinds of changes. As you may know, there is lot of incompatible code between Python 2 and 3. Some of the most obvious incompatible changes in Python 3 that will break Python 2 code (and vice-versa) are the conversion of the print statement (print) to the print function (print), and the updating of rawinput to input.
- While it may seem counter-intuitive, you can write Python code which is source-compatible between Python 2 & 3. It does lead to code that is not entirely idiomatic Python (e.g., having to extract the currently raised exception from sys.excinfo1 ), but it can be run under Python 2 and Python 3 without using 2to3 as a translation step.
- I think writing Python 2 and 3 compatible code is an important skill, so lets check what it entails. Python 2.x is legacy, Python 3.x is the present and future of the language - Python2orPython3 wiki. Summary Best Practices. The best place to start is the HOWTO: Porting Python 2 Code to Python 3 which nicely summarizes the important.
Contents:¶
- What’s New
- Overview: Easy, clean, reliable Python 2/3 compatibility
- Quick-start guide
- Cheat Sheet: Writing Python 2-3 compatible code
- Imports
- What else you need to know
- Automatic conversion to Py2/3
- Frequently Asked Questions (FAQ)
- Standard library incompatibilities
- Older interfaces
- Changes in previous versions
- Licensing and credits
- API Reference (in progress)
The title of this tutorial is a bit misleading, but I will explain that.
Note: This tutorial uses methods from my other tutorial, What Python Version is This? It may be best to read that tutorial first.
As you may know, there is lot of incompatible code between Python 2 and 3. Some of the most obvious incompatible changes in Python 3 that will break Python 2 code (and vice-versa) are the conversion of the print statement (
print
) to the print function (print()
), and the updating of raw_input()
to input()
.Python 2 and 3 compatible code #54. Closed molsky opened this issue Dec 23, 2015 5 comments Closed Python 2 and 3 compatible code #54.
If you at any point want to make a Python 2 and 3 compatible version of your script, you need to find a way to bridge these two major changes, but how do you bridge them? Omnifocus pro 2 12 download free. Read on to find out how.
While all code is Python 2 and 3 compatible, any
Exceptions
are from Python 3.3+.The print
ing Press
There are three different ways you can solve this issue. I will list them in order from “Ideal fix” to “It will do”. Ommwriter 1 613. Do note this is not an exhaustive list of methods, there are other ways to do this. I am just listing the three most popular.
- You can use the
__future__
module using the syntaxfrom __future__ import print_function
to bring the full-fledged Python 3print()
function to your Python 2 script.#! /usr/bin/env/python # -*- coding: utf-8 -*- from __future__ importprint_function importsys print('nThis is the Python 3 print function in a Python 2 script!', end=' Hehehe.') sys.exit(0) This import brings the entire Python 3 print function to Python 2, including the newsep=' '
,end='n'
, andfile=f
parameters. The entire import is ignored in Python 3, so your interpreter will not run that line. This is the best method in my eyes. Although you are not going to be mixing the statement and function in the same script, you get to benefit from the superior internal workings and train you for the inevitable switch to a Python 3 only world. This method is also the most widely recommended method by multiple sites and companies, such as Canonical Ltd. (the maintainers of Ubuntu Linux) on their Python 3 page. - Although Python 3 changed the way you
print
text, it did not change the destination of the text; it all goes tosys.stdout
, AKA the console window. This method only adds one new line to you code (assuming you are not alreadyimport
ingsys
). Using this instead ofprint()
, you can a send your text directly to the console, like so:#! /usr/bin/env/python # -*- coding: utf-8 -*- importsys sys.stdout.write('' This text was sent directly to the console window without using print!'') sys.exit(0) There are a few differences between usingprint()
andsys.stdout.write
, though. First, all new lines must be explicitly stated; it doesn’t write them for you (like the print statement). Second, everything must be a string, so boolean (True
,False
) and float/integer values must be converted to a string before it can be displayed, or you’ll hit an error. However, you simply need to wrap your text in astr()
to fix that. - Finally, you can use the faux print function in Python 2 added specifically to help port code from 2 to 3. I advise to stay away from this at all costs, unless you are 120% sure nobody will run attempt to your script on a really old version of Python. In addition, it is not even the full print function. It acts and is interpreted exactly like the statement, but uses parentheses to avoid a
SyntaxError
on Py3. It also incorrectly interprets the.format()
method, creating anAttributeError
on 3.As I said, try to avoid this method at all costs.#! /usr/bin/env/python # -*- coding: utf-8 -*- importsys print('I'm using the faux print function in Python 2. Boo hoo hoo?') sys.exit(0)
So, you want my input
?
Like
print
, input
has a few solutions, but with on out of the scope of this tutorial, I will example the easier solution. Since raw_input()
was removed in Python 3 and input()
took its place, we need to devise a way to detect the version of Python being run and use the proper input()
function.This solution is not completely my own. I found it somewhere on Stack Overflow, and modified it just a bit. ? The code below
if __name__ '__main__':
is what we are interested in here, but I have provided a full working example. I advise keeping the lines in the global namespace. Wrapping it in a function does not permit for per-case input normalization, a topic best explained in another tutorial.Python 2 And 3 Compatible Codex
#! /usr/bin/env/python |
# -*- coding: utf-8 -*- |
from __future__ importprint_function |
importsys |
defmain(): |
# Ask a question |
question=get_input('nWhat do you have to say for yourself? ') |
# Send back user input |
print(question) |
sys.exit(0) |
if__name__'__main__': |
# Support Python 2 and 3 input |
# Default to Python 3's input() |
get_input=input |
# If this is Python 2, use raw_input() |
ifsys.version_info[:2] <= (2, 7): |
get_input=raw_input |
main() |
It simply detects what version of Python is being used, and uses that version’s form of input. You may also notice I’ve used
from __future__ import print_function
to send back the input. Practice what I preach. ?Python 2 And 3 Compatible Codes
There technically is no Py2 and Py3 compatible input. The two, while seemingly the same on the outside, are different on the inside and completely incompatible with each other. Because of this, we have to use Python version detection to allow us to use the proper input implementation. This method allows for input normalization, but again, that is another tutorial. ?
Python 2 To Python 3
You now know how to bridge the two most major changes between Python 2 and 3. You may not use this at first, but it could come in handy later on. I think this quote from Swaroop C H‘s great book, A Byte of Python, sums up this lesson perfectly. ?
Python 2 Vs 3
Remember that once you have properly understood and learn to use either of them [Python 2 or 3], you can easily learn the changes between the two versions and adapt easily. The hard part is learning programming and understanding the core Python language itself.