-
-
Notifications
You must be signed in to change notification settings - Fork 32.5k
Description
Feature or enhancement
Proposal:
Currently i18n in Python usually looks like this:
msg = _('Hello {name}').format(name=name)
msg = ngettext('{n} snake', '{n} snakes', n).format(n=n)
This isn't super pretty and prone to errors such as calling .format()
inside the gettext call instead of outside.
It also leads to people being lazy and creating strings that may not work properly depending on the target language, because multiple positional placeholders are used:
flash(_('Category "{}" moved to "{}"').format(cat.title, target_cat.title))
f-strings obviously do not work, because it'd be just like calling .format()
inside gettext.
But now that we have t-strings, this can be solved:
msg = _(t'Hello {name}')
msg = ngettext(t'{n} snake', t'{n} snakes', n)
flash(_(t'Category "{cat.title}" moved to "{target_cat.title}"'))
(Maybe an interesting fact: A less powerful version of this exists in Jinja2 templates for a very long time - it lets you use plain variables inside {% trans %}
and uses the variable name during extraction, but the value during translation.)
Using t-strings for i18n also provides a bunch of advantages, such as avoiding positional arguments and shorter line lengths.
The tricky part is of course how to convert the expressions from the t-string interpolation to names that are suitable in format strings and translations. Obviously nobody wants "real" code inside a gettext .po file.
My proposed way to solve this is to derive a format string field name from the expression, and reject anything that's too complex or too dynamic. My current implementation (I will open a PR shortly after opening this issue) covers simple cases such as plain variables, accessing attributes and items, and calling a method w/o arguments.
Has this already been discussed elsewhere?
There is no discussion (yet) because I actually started hacking on this feature during EuroPython to see if it's feasible at all, and I only read the issue template here when I was about to open a PR. If you believe there should be a discussion about this in the forum, I'll be happy to open a thread (edit: done, here's the thread).
Linked PRs
Metadata
Metadata
Assignees
Labels
Projects
Status