A print function for compatibility with 3.0 ?
Python 3.0 comes with a builtin print function which breaks old code. In order to write code wich is compatible both with the 2.x series and with the 3.x series, I'm using the following Print function
import sys
def Print(*values, **kwd):
fout = kwd.get("file", sys.stdout)
sep = kwd.get("sep", " ")
end = kwd.get("end", "\n")
w = fout.write
if values:
w(str(values[0]))
for v in values[1:]:
w(sep)
w(str(v))
w(end)
if sys.version_info[0] >= 3:
Print = eval("print")
In my programs, I use this Print function as if it was 3.0's print. The difference is that it still runs with python 2.5, like in this example
Print("Hello", "world", sep="--", end=" !\n")
What do you you think of this ? Is there a better thing to do ?
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
You could also get the python version
print sys.version_info
and then use the appropriate "print input_var" or "print(input_var)" depending on whether version is > 2.5.
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
Good point. Time to download 3.0 and do a search of comp.lang.python. It has undoubtedly been discussed. For now, I will have to form the habit of using
print("hello world")
as that works in both 2.5 and 3.0.
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
Good point. Time to download 3.0 and do a search of comp.lang.python. It has undoubtedly been discussed. For now, I will have to form the habit of using
print("hello world")
as that works in both 2.5 and 3.0.
Unfortunately
print("hello", "world")
doesn't work as expected in 2.5 :=)
I modified the Print function above to get a version which should work with 2.4, 2.5, 2.6 and 3.0
# module cbprint
# Defines a Print function to use with python 2.x or 3.x
__all__ = ["Print"]
import sys
try:
Print = eval("print")
except SyntaxError:
try:
D = dict()
exec("from __future__ import print_function\np=print", D)
Print = D["p"]
del D
except SyntaxError:
del D
def Print(*args, **kwd):
fout = kwd.get("file", sys.stdout)
w = fout.write
if args:
w(str(args[0]))
sep = kwd.get("sep", " ")
for a in args[1:]:
w(sep)
w(str(a))
w(kwd.get("end", "\n"))
Usage (all versions, tested on 2.5 and 3.0):
from cbprint import Print
Print("Hello", "world")
The problem is that many existing libraries might be unable to run with python 3.0 for a while, and the default python implementation on many systems (like linux) may still be python 2.5 for a while. This happened in the past with python 1.5. So I think we should be concerned with writing code which works both for 2.5 and 3.0.
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691