Printing in Python 3.0
I’ve been playing with Python 3.0 recently. It does some nice things, like fixing the asymmetry between reading from stdin and writing to stdout by making print a function rather than a statement:
print('Square-root of', x, 'is', math.sqrt(x))
There’s also a new (C#-inspired?) syntax for string formatting:
output = 'Square-root of {0:g} is {1:g}'
print(output.format(x, math.sqrt(x)))
It’s a shame that they haven’t closed the loop by providing a printf function of some kind. Still, I suppose it isn’t hard to write one:
def printf(format_string, *args, **kwargs):
print(format_string.format(*args, **kwargs))
March 31st, 2008 at 12:34 am
Ideally, to maintain the uniformity that the new print functions introduce, we would need to provide the same interface that print() provides.
Say, something like this should work.
printf(format_string, blah, blah, file=stderr)
I haven’t looked into all the options of Python 3.0’s format function, but if there is a conflict, in the key-word arguments with that of the print function, it could get tricky.
Without a printf(), we can still write, something that looks very similar:
print(format_string.format(blah, blah), file=stderr)
Without printf, we need to type “.format(” and its matching “)”; 9 more characters.
The opinion on whether the savings is worth enough to add another built-in is bound to differ from developer to developer. I think, we still have a few months more to wait and see.
April 1st, 2008 at 2:45 pm
Some good points Jayce. I expect that plenty of folk will be opposed to the idea of introducing a new built-in, for understandable reasons.
However, in a language that prides itself on clarity, and that is prepared to break backwards compatibility to the point that “hello world” no longer works in order to achieve this, I confess to being a little disappointing that a more direct, less clumsy approach to formatted printing isn’t yet available.
Don’t get me wrong; there’s a number of things about the new approach to string formatting that I like. It is more flexible and powerful, for one. And I think I prefer {0}, {1}, etc, as a placeholder syntax. What I don’t really like is the relative unreadability of code like this:
print(”Content-type: {0[.mp4]}”.format(mimetypes.types_map))
OK, you can rewrite this as
format_string = “Content-type: {0[.mp4]}”
print(format_string.format(mimetypes.types_map))
But I think a printf in this case is even easier to read.