#python2vs3
Explore tagged Tumblr posts
rescuedbycode · 9 years ago
Text
Python 2 vs 3: All Hail the Print Function
This is part of an ongoing series of posts by Keith Bradnam and Michelle Gill that chronicle some lessons that we have learned while writing UNIX and Python to the Rescue! Keith will be discussing his experiences in switching from Perl to Python while Michelle will cover differences between Python 2 and 3.
One of the more well-known changes in Python 3 is the upgrading of print from its lowly Python 2 status as a statement to a genuine, first-class function in Python 3. In most cases, this simply means a set of parentheses need to be added.
Here is an example using the print statement from Python 2:
# Python 2 uses a print statement print 'The Castle of aaarrrrggh.'
And here is the same example adapted for Python 3:
# Python 3 uses a print function print('The Castle of aaarrrrggh.')
As we will learn in “UNIX and Python to the Rescue!”, later versions1 of Python 2 have a future module that allows you import things from the future (Python 3). What's more, Python 3 code will run just fine with this import, albeit without any actual changes since Python 3 is the future. This means you can write code that is version independent using the future module.
Here is an example of the above code written in a way that is independent of Python 2 vs 3:
from __future__ import print_function # Python 2 and 3: print('The Castle of aaarrrrggh.')
Now that we understand how to update code to work with Python 3, we might want to know why this is useful. There are actually many technical reasons, but the main one is consistency with other functions. In Python 2, print was something of an outlier in that it often worked like a function, but not always. And its syntax reflected this.
For example, the following code produces an error in Python 2:
[print x for x in range(5)] # Python 2: # SyntaxError: invalid syntax
However, this will work in Python 2 (and 3) when print is an actual function:
from __future__ import print_function [print(x) for x in range(5)] # Python 2 and 3: # 0 # 1 # 2 # 3 # 4
This introduction is intended provide a basic understanding of one of the most commonly encountered differences in Python 2 vs 3 and explains why the change is—in most cases—an improvement. It's also important to understand how to write code that is independent of which Python version is being used.
The future module is implemented starting with Python 2.6. ↩︎
1 note · View note