[Python-ideas] Briefer string format

Stefan Behnel stefan_ml at behnel.de
Sun Aug 9 13:01:11 CEST 2015


Andrew Barnert via Python-ideas schrieb am 09.08.2015 um 12:27:
> do you really never need formatting in log messages? Do you only use
> highly structured log formats? I'm always debug-logging things like
> "restored position {}-{}x{}-{} not in current desktop bounds {}x{}" or
> "file '{}' didn't exist, creating" and so on, and this proposal would
> help there as well.

Sure, I use formatting there. But the formatting is intentionally done
*after* checking that the output passes the current log level. The proposal
is about providing a way to format a string literal *before* anyone can do
something else with it. So it won't help for logging. Especially not for
debug logging.

Also, take another look at your examples. They use positional formatting,
not named formatting. This proposal requires the use of named formatting
and only applies to the exact case where the names or expressions used in
the template match the names used for (local/global) variables. As soon as
the expressions become non-trivial or the variable names become longer (in
order to be descriptive), having to use the same lengthy names and
expressions in the template, or at least having to assign them to new local
variables before-hand only to make them available for string formatting,
will quickly get in the way more than it helps. With .format(), I can (and
usually will) just say

    output = "writing {filename} ...".format(
        filename=self.build_printable_relative_filename(filename))

rather than having to say

    printable_filename = self.build_printable_relative_filename(filename)
    output = f"writing {printable_filename} ..."  # magic happening here
    del printable_filename  # not used anywhere else

As soon as you leave the cosy little niche where *all* values are prepared
ahead of time and stored in beautiful local variables with tersely short
and well-chosen names that make your string template as readable as your
code, this feature is not for you any more.

Stefan



More information about the Python-ideas mailing list