[Python-ideas] String interpolation for all literal strings
Barry Warsaw
barry at python.org
Thu Aug 6 20:16:16 CEST 2015
On Aug 06, 2015, at 03:23 PM, Nick Coghlan wrote:
>If we went down that path, then string.Template would provide the most
>appropriate inspiration for the spelling, with "$" as the escape
>character rather than "\". For regular expressions, the only
>compatibility issue would be needing to double up on "$$" when
>matching against the end of the input data.
Well, you've pretty much reinvented flufl.i18n :) except of course I had to
use _() as a marker because I couldn't use a special prefix.
(There are a few knock-on advantages to using a function for this too, such as
translation contexts, which become important for applications that are more
sophisticated than simple command line scripts.)
Having used this library in lots of code myself *and* interacted with actual
translators from the Mailman project, I really do think this approach is the
easiest both to code in and to get high quality less error-prone translations.
The only slightly uncomfortable bit in practice is that you can sometimes have
local variables that appear to be unused because they only exist to support
interpolation. This sometimes causes false positives with pyflakes for
example.
flufl.i18n doesn't support arbitrary expressions; it really is just built on
top of string.Template. But TBH, I think arbitrary expressions, and even
format strings are overkill (and possibly dangerous) for an i18n application.
Dangerous because any additional noise that has to be copied verbatim by
translators is going to lead to errors in the catalog. Much better to leave
any conversion or expression evaluation to the actual code rather than the the
string. The translated string should *only* interpolate - that's really all
the power you need to add!
>That has a couple of nice refinements over the subsequent simpler PEP
>292 interpolation syntax, in that it allows "$obj.attr.attr",
>"$data[key]" and "$f(arg)" without requiring curly braces.
flufl.i18n also adds attribute chasing by using a customized dict-subclass
that parse and interprets dots in the key.
One other important note about translation contexts. It's very important to
use .safe_substitute() because you absolutely do not want typos in the catalog
to break your application.
Cheers,
-Barry
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 819 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150806/1be89ac7/attachment.sig>
More information about the Python-ideas
mailing list