Monday, December 22, 2008

Python 3.0 and print function

I have been following the python mailing list for quite some time now. I recommend it for any pythonista who's not afraid of a bit of spam and flame war here and there.

There has been a lot of discussion and arguments about a change in Python 3.0 in which print is a built-in function now instead of a language-specific statement. The arguments started flowing in to the mailing list just minutes after Python 3.0 final was officially released.

Most complaints seem to revolve around the fact that *now* we have to write extra two parenthesis, ie. print("something") instead of print "something". Let us ignore that complaint for now, as it is minor (not to mention pointless) issue, something to get used to and easily solved with IDEs. Besides, we all *know* how to use functions, right? This is a non-issue.

Another (much larger) complaint is about string formatting (PEP-3101 - Advanced String Formatting), which is a very big improvement over the formatting using "%". New built-in function, format(), has been introduced along with (so-called) "Format Specification mini-language" to specify and control formatting. Quite powerful, if you ask me.

Particularly interesting formatting option is formatting of positive and negative numbers (a sign option). Consider implementing this in the old syntax:

print(format(-123456,'#> 20'))
print(format(123456, '#> 20'))
print(format(123456, '#>+20'))

Furthermore, you can implement __format__() method in your classes, which will be called by the format() built-in function for producing a formatted version of the object. However, implementing formatting specification is up to you - you can use the standard formatting syntax or implement your own.

Bottom line is, Python 3.0 brought a lot of changes and improvements; those changes have been discussed and polished over a period of several years prior to releasing the final version. What I don't understand is those people who are complaining about it now, instead of doing it before and contributing to those discussions. It will get some time to get used to the new changes, sure; but don't dismiss them straight away - give it a chance and try it out. You will soon realize that those changes are in fact good ones.

No comments: