[Python-ideas] One way to do format and print (was: Desperate need for enhanced print function)

Chris Angelico rosuav at gmail.com
Mon Sep 7 10:23:13 CEST 2015


On Mon, Sep 7, 2015 at 3:46 PM, Sven R. Kunze <srkunze at mail.de> wrote:
> On 07.09.2015 01:48, Nick Coghlan wrote:
>>
>> As such, it currently appears likely that Python 3.6 will allow you and
>> your peers to write output messages like this:
>>
>>      print(f"Hello, I am {b}. My favorite number is {a}.")
>>
>> as a simpler alternative to the current options:
>>
>>      print("Hello, I am ", b, ". My favorite number is ", a, ".", sep="")
>>      print("Hello, I am " + b + ". My favorite number is " + str(a) + ".")
>>      print("Hello, I am {}. My favorite number is {}.".format(b, a))
>>      print("Hello, I am {b}. My favorite number is
>> {a}.".format_map(locals()))
>>      print("Hello, I am %s. My favorite number is %s." % (b, a))
>
>
> Wow, that is awesome and awkward at the same time.
>
> Shouldn't Python 3.7 deprecate at least some of them? (Just looking at the
> Zen of Python and https://xkcd.com/927/ )

Which would you deprecate?

     print("Hello, I am ", b, ". My favorite number is ", a, ".", sep="")

The print function stringifies all its arguments and outputs them,
joined by a separator. Aside from the 2/3 compatibility requirement
for single-argument print calls, there's no particular reason to
deprecate this. In any case, this isn't "yet another way to format
strings", it's a feature of print.

     print("Hello, I am " + b + ". My favorite number is " + str(a) + ".")

String concatenation is definitely not going away; but even without
PEP 498, I would prefer to use percent formatting or .format() above
this. Its main advantage over those is that the expressions are in the
right place, which PEP 498 also offers; if it lands, I fully expect
3.6+ code to use it rather than this. But the _functionality_ can't be
taken away.

     print("Hello, I am {}. My favorite number is {}.".format(b, a))

This one is important for non-literals. It's one of the two main ways
of formatting strings...

     print("Hello, I am %s. My favorite number is %s." % (b, a))

... and this is the other. Being available for non-literals means they
can be used with i18n, string tables, and other transformations.
Percent formatting is similar to what other C-derived languages have,
and .format() has certain flexibilities, so neither is likely to be
deprecated any time soon.

     print("Hello, I am {b}. My favorite number is {a}.".format_map(locals()))

This one, though, is a bad idea for several reasons. Using locals()
for formatting is restricted - no globals, no expressions, and no
nonlocals that aren't captured in some other way. If this one, and
this one alone, can be replaced by f-string usage, it's done its job.

ChrisA


More information about the Python-ideas mailing list