Proposal: use str.format instead of percentage formatting for core-scripts #120453
Labels
No Label
Interest
Alembic
Interest
Animation & Rigging
Interest
Asset Browser
Interest
Asset Browser Project Overview
Interest
Audio
Interest
Automated Testing
Interest
Blender Asset Bundle
Interest
BlendFile
Interest
Collada
Interest
Compatibility
Interest
Compositing
Interest
Core
Interest
Cycles
Interest
Dependency Graph
Interest
Development Management
Interest
EEVEE
Interest
EEVEE & Viewport
Interest
Freestyle
Interest
Geometry Nodes
Interest
Grease Pencil
Interest
ID Management
Interest
Images & Movies
Interest
Import Export
Interest
Line Art
Interest
Masking
Interest
Metal
Interest
Modeling
Interest
Modifiers
Interest
Motion Tracking
Interest
Nodes & Physics
Interest
OpenGL
Interest
Overlay
Interest
Overrides
Interest
Performance
Interest
Physics
Interest
Pipeline, Assets & IO
Interest
Platforms, Builds & Tests
Interest
Python API
Interest
Render & Cycles
Interest
Render Pipeline
Interest
Sculpt, Paint & Texture
Interest
Text Editor
Interest
Translations
Interest
Triaging
Interest
Undo
Interest
USD
Interest
User Interface
Interest
UV Editing
Interest
VFX & Video
Interest
Video Sequencer
Interest
Virtual Reality
Interest
Vulkan
Interest
Wayland
Interest
Workbench
Interest: X11
Legacy
Blender 2.8 Project
Legacy
Milestone 1: Basic, Local Asset Browser
Legacy
OpenGL Error
Meta
Good First Issue
Meta
Papercut
Meta
Retrospective
Meta
Security
Module
Animation & Rigging
Module
Core
Module
Development Management
Module
EEVEE & Viewport
Module
Grease Pencil
Module
Modeling
Module
Nodes & Physics
Module
Pipeline, Assets & IO
Module
Platforms, Builds & Tests
Module
Python API
Module
Render & Cycles
Module
Sculpt, Paint & Texture
Module
Triaging
Module
User Interface
Module
VFX & Video
Platform
FreeBSD
Platform
Linux
Platform
macOS
Platform
Windows
Priority
High
Priority
Low
Priority
Normal
Priority
Unbreak Now!
Status
Archived
Status
Confirmed
Status
Duplicate
Status
Needs Info from Developers
Status
Needs Information from User
Status
Needs Triage
Status
Resolved
Type
Bug
Type
Design
Type
Known Issue
Type
Patch
Type
Report
Type
To Do
No Milestone
No project
No Assignees
5 Participants
Notifications
Due Date
No due date set.
Dependencies
No dependencies set.
Reference: blender/blender#120453
Loading…
Reference in New Issue
No description provided.
Delete Branch "%!s(<nil>)"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Motivation
str.format
syntax) is generally preferred for modern Python (in tutorials & documentation).scripts/startup
percentage-formatting is no longer the preferred method of string formatting used by Blender developers.Pros & Cons
Pros:
Developers who maintain modern code-bases outside of Blender don't have to learn percentage string formatting since
f-string
&str.format
use same mini-language.Clearer for closely grouped formatting:
"0x%.2x%.2x%.2x%.2x" % color
:%-format
."0x{:02x}{:02x}{:02x}{:02x}".format(*color)
:str.format
.Also when
.
is part of the string:"%s%.3d.fbx" % (name, index)
:%-format
."{:s}{:03d}.fbx" % (name, index)
:str.format
.Reduced ambiguity with multiple arguments:
"%d %s" % var
:%-format
."{:d} {:s}".format(*var)
:str.format
.%-format
reads like it could be a bug, it's only valid ifvar
is a tuple but this relies on checking the surrounding context to verify.By contrast
str.format
requires explicitly unpackingvar
making the developers intention clear.There is also the case where you may want to print a tuple, requiring awkward single-tuple syntax:
"Example %r text" % (var,)
:%-format
."Example {:r} text".format(var)
:str.format
.str.format
is similar tofmt
library which is becoming more widely used in C++ code.Cons:
str.format
is over twice as slow."(%d): %s" % (a, b)
compared to..."({:d}): {:s}".format(a, b)
.While performance aspect shows up in micro-benchmarks the absolute times are both very small (~112 vs 255 nanoseconds in my tests).
If we were to consider these kinds of changes to be deal breakers then there would be other changes we could make with the Python API use - such as avoiding function call overhead in the UI... nevertheless being slower is a down side - so it needs to be mentioned.
Proposal
str.format
for all scripts in:scripts/startup/
str.format
in user facing scripts:doc/python_api/examples/
scripts/templates_py/
str.format
over percentage-formatting elsewhere (percentage formatting can be phased out for Blender's scripts).Details
Always use type specifiers for clarity.
Use positional arguments (with an exception for complex cases, see Keyword arguments below)
Before:
After:
Before:
After:
In situations where it's more difficult to keep track of positional arguments, developers may used keyword arguments:
Rationale for str.format over f-strings
The reasons to propose
str.format
over f-strings are as follows:str.format
is a reasonable one-size-fits-(practically)-all solution for core scripts, the existing formatting method can be replaced withstr.format
in a straightforward way.While the last point is quite subjective, the issue with translated labels mean even if we wanted to use f-strings we would have to avoid them and keep track of when f-strings can/can't be used, apply this rule consistently, take into account when reviewing patches etc - which I'd rather avoid.
Further, support for passing keywords to
str.format
largely addresses the same pain-point that f-strings do for more complex situations.Other Notes
How come it's not going to be an issue with
str.format
? Once you changed the format string the translation would need to be changed anyway 🤔@ChengduLittleA this is my understanding although @mont29 may have more insights here.
The translation system currently receives
"Rename %d %r"
and uses a lookup table to replace that exact string.If we use
str.format
the string would be"Rename {:d} {!r}"
which is roughly equivalent.From what I can see f-strings can't be used for translated strings because translation lookups on evaluated strings wont work e.g.
iface_(f"Rename {a+b} {self.modifier.name}")
will fail because it would use the result ofa+b
andself.modifier.name
in the lookup.Even if it could be made to work having code inlined seems like it's not ideal for the translation system to include as changes to the code would cause the string literal to change.
👍 LGTM!
Personally I've always liked
%
formatting, but that's just because of familiarity since I've been usingprintf()
for so long. I stand behind all the advantages ofstr.format()
described in this design task though. Especially with f-strings becoming more prevalant (especially in software that doesn't need translation) the format string mini-language is getting more widely known too, so let's go!I'm not sure I really see the urgency/actual benefit of this change, but am also not opposed to it. Only real downside I see to using
str.format
is that it's somewhat more verbose than the%
C-style way. The performances issues noted in https://stackoverflow.com/questions/62566526/percentage-formatting-twice-as-fast-as-f-strings-in-python-3-x also still seems valid? But this indeed also matches our C++fmt
lib syntax...Regarding f-strings, the problems with translations arise even before looking up for translations during execution: we cannot even extract f-strings currently.
I18N message extraction uses python's AST module to find strings, and f-strings are... not strings at AST level - never found a way to get anything usable from them at that level of abstraction. In any case, I'm also not sure how we would deal with such strings at translation level. Even the basic
%
syntax is already an issue (people forget some, or modify their order, and with C-code this can even lead to crashes). I would rather not have interpreted python code in these translations strings! ;)So as much as I love f-strings, they are indeed an absolute no-go for any UI-related message.
@ChengduLittleA indeed the existing translations will have to be updated, but like @ideasman42 said, it's only a change of syntax, so while annoying to have to deal with it, it's not really a big issue either.
@mont29 the performance issue is still valid unfortunately and something I should have mentioned in the proposal, although this is an area of CPython that had some work - the improvements don't seem significant (in some of my tests str.format is ~40% slower).
Comparing
"%s %s %s"
with"{:s} {:s} {:s}"
the old-style is around twice as fast perhaps a little faster taking out the time to iterate, however this is comparing very small values.0.000000112
seconds.0.000000255
seconds.112 vs 255 nano-seconds, which I think can be overlooked as I doubt we could even measure the difference from Blender's UI in practice. This was a concern previously but since we're no longer writing exporters in Python, the performance of formatting large amounts of data is less of an issue.
Added pros & cons to the proposal.
Submitted PR to use
str.format
!120552.As I also mentioned in #120552, this is not an entirely fair comparison, as these two do not do the same thing.
"%s %s %s"
should be compared with"{!s} {!s} {!s}"
(if you want to enforce the call tostr()
) or"{} {} {}"
(if the arguments are already strings).In those cases I think it would be fine to keep using
%
-formatting. And then there's of course also the opportunity for benchmarking, writing those results in a comment, and explaining the choices made. IMO such specific cases don't have to stand in the way of the majority of Blender's Python code switching tostr.format
.True,
{:s}
/{!s}
/{}
have different results when micro-bench marking (I don't have the numbers handy).Sine the overall speed is so small I'm not that worried about this, although it's annoying to opt for a measurably slower option.
If this kind of performance was a concern though - I think there are quite a few ways we could when this back (RNA function calls can probably be optimized for e.g.).
Right, even in this case though I think it's reasonable that there is a measurable real world difference that's not in the sub <10 millisecond realm.
Committed
0e3b594edb
& updated the developer handbook, closing.@ideasman42 Just a note on the performance discrepancy mentioned for f-strings: It really depends on how they are used. Taking the test script from your SO question (https://stackoverflow.com/questions/62566526/percentage-formatting-twice-as-fast-as-f-strings-in-python-3-x?newreg=eda4a27f8a8647f6904f31dfa7f1c12b), if you remove the explicit string specifiers (e.g.
{a:s}
->{a}
, etc.), then f-strings are actually notably faster than the old modulo style syntax, and they are producing the same resulting string. There are probably cases where one or the other will be faster, depending on how in-depth the formatting specifiers are, and how many are used. For reference, these are the numbers I got when I made the above change (and also changed the.format()
to not bother with:s
as well):This is on Python 3.12 (the superfluous
'%s'
in the output should just be ignored). Also, there are some other reputable Python learning source that contend that f-strings are faster: https://realpython.com/python-f-strings/#comparing-performance-f-string-vs-traditional-tools@T-112 this is interesting & strange that f-strings are faster without the
:s
. Replied to the stackoverflow post with these findings.