[Python-ideas] Printf function?
Nick Coghlan
ncoghlan at gmail.com
Sun May 13 16:44:02 CEST 2012
On Sun, May 13, 2012 at 10:49 AM, Carl M. Johnson
<cmjohnson.mailinglist at gmail.com> wrote:
> I was looking at this jokey page on the evolution of programming language syntax -- http://alan.dipert.org/post/153430634/the-march-of-progress -- and it made me think about where Python is now. The Python 2 version of the example from the page is
>
> print "%10.2f" % x
>
> and the Python 3 is
>
> print("{:10.2f}".format(x))
The main reason the format() builtin exists is to easily format single fields:
>>> x = 5.0
>>> print(format(x, "10.2f"))
5.00
The new formatting system doesn't scale down as well as the old one,
so "format a single field value with no surrounding text" is handled
as a special case.
> Personally, I prefer the new style {} formatting to the old % formatting, but it is pretty busy when you want to do a print and format in one step. Why not add a printf function to the built-ins, so you could just write
>
> printf("{:10.2f}", x)
>
> Of course, writing a printf function for oneself is trivial and "not every three line function needs to be a built-in," but I do feel like this would be a win for Python's legibility.
The problem is that you have two competing uses for your arguments -
"print" wants to accept "file", "end", etc, while format() wants to
accept *args and **kwds). It's better to keep the two separate and
allow people to compose them as they wish.
For myself, aside from temporary debugging messages, I rarely call
"print" directly in any non-trivial code - instead I'll have a
"display" utility module that tweaks things appropriately for the
specific application. Maybe it will redirect to logging, maybe it will
print directly to a stream or to a file - the utility module gives me
a single point of control without having to change the rest of the
script.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list