[Python-ideas] Combine f-strings with i18n

Hans Polak hpolak at polak.es
Tue Sep 18 04:12:06 EDT 2018


On 17/09/18 19:42, Stephen J. Turnbull wrote:
>   > That's why I would like to see a parameter that can be passed to
>   > the f-string.
>
> This doesn't make sense to me.
If I get a request in English, I need to return English.
If I get a request in French, I need to return French.

# At the start of the app, the languages get loaded in memory.
translate = translation('app','.locale')
translate.install()
es = translation('app','.locale',languages=['es'])
es.install()

# Get the preferred user language from the http request T(_('Hello {user}...'), user_language,user=user)

def T(translatable_string, language=None, *args, **kwargs):

     if 'es' == language:

         # Return translated, formatted string return es.gettext(translatable_string).format(**kwargs)

     # Default, return formatted string return translatable_string.format(**kwargs)

>    Such configurations are long-lasting.
If it is for the whole app, yes. Not if it is just the request.

1. No translation, just a regular f-string.
2. App translation. The f-string gets translated to the configured 
language. Long lasting configuration.
3. On the fly translation. The string gets translated to the language 
passed as an argument as required.

> What could work is an extension to the formatting language.  I suggest
> abusing the *conversion flag*.  (It's an abuse because I'm going to
> apply it to the whole f-string, while the current Language Reference
> says it's applied to the value being formatted.[1])  This flag would only
> be allowed as the first item in the string.  The idea is that
> `f"{lang!g}Hello, {user}!"` would be interpreted as
Excellent. The syntax is unimportant to me.

Cheers,
Hans

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180918/f74c7cb9/attachment.html>


More information about the Python-ideas mailing list