Best-practice for formatted string literals and localization?

Chris Angelico rosuav at gmail.com
Mon Nov 30 13:58:43 EST 2020


On Tue, Dec 1, 2020 at 5:31 AM Hartmut Goebel
<h.goebel at crazy-compilers.com> wrote:
>
> Hi,
>
> formatted string literals are great, but can't be used together with
> localization:
>
>     _(f"These are {count} stones")
>
> will crash babel ("NameError: name 'count' is not defined". And even it
> it would succeed, the *evaluated* string would be passed to "_(…)",
> resulting in a not-translated string.
>
> Is there a better solution than
>
>     _("These are {count} stones").format(count=count)
>
> ("Better" = without passing args or kwargs to `format()`)
>

Not really, no. The whole point of f-strings is keeping the template
and the interpolations together, and the whole point of localization
tools is keeping them apart. I'm not sure why you're getting that
NameError, but the more fundamental problem is still there; you
absolutely have to do the localization on the constant string with the
template markers still in it, and only afterwards do the
interpolation, so you're basically left with what you're already
doing.

It might be possible to do something with an import hook that
translates _f"...." into _("....").format(...) but that would be the
best you'd get.

ChrisA


More information about the Python-list mailing list