[Python-ideas] Briefer string format
Andrew Barnert
abarnert at yahoo.com
Sun Aug 9 14:26:57 CEST 2015
On Aug 9, 2015, at 04:01, Stefan Behnel <stefan_ml at behnel.de> wrote:
>
> 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.
Maybe it's just me, but 90%+ of my debug log messages are really only dev log messages for the current cycle/sprint/whatever, and I strip them out before pushing. So as long as they're not getting in the way of performance for the feature I'm working on in the environment I'm working in, there's no reason not to write them as quick&dirty as possible, forcing me to decide which ones will actually be useful in debugging user problems, and clean up and profile them as I do so. And quite often, it turns out that wasting time on a str.format call even when debug logging is turned off really doesn't have any measurable impact anyway, so I may end up using it in the main string or in one of the %s arguments anyway, if it's more readable that way.
> 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.
Yes, but that's because with simple messages in 3.5, positional formatting is more convenient. Under the proposal, that would change. Compare:
"file '{}' didn't exist, creating".format(fname)
"file '{fname}' didn't exist, creating".format(fname=fname)
"file '{fname}' didn't exist, creating".format(**vars())
f"file '{fname}' didn't exist, creating"
The second version has me repeating the name three times, while the third forces me to think about which scope to pass in, and is still more verbose and more error-prone than the first. But the last one doesn't have either of those problems. Hence the attraction.
And of course there's nothing forcing you to use it all the time; when it's not appropriate (and it won't always be), str.format is still there.
More information about the Python-ideas
mailing list