[Python-ideas] Combine f-strings with i18n

Hans Polak hpolak at polak.es
Fri Sep 14 05:02:44 EDT 2018


I have recently updated my code to use the more pythonic f-string 
instead of '{}'.format()

Now, I want to start on the road to multilingual internationalization, 
and I run into two problems. The first problem is that f-strings do not 
combine with i18n. I have to revert to the '{}'.format() style.

The second problem is that I need to translate strings on the fly. I 
propose to add a f''.language() method to the f-string format.


Example:

user = 'Pedro'

f'Hi {user}' would be translated to 'Hola Pedro' if the locale were set 
to Spanish.

f'Hi {user}'.language('es_ES') would be translated in the same way.


To extract translatable strings from the source code, the source code 
could contain a 'HAS_LOCALES' flag (or something similar) at the top of 
the code. This way, the pygettext.py program would know that 
translatable f-strings are within the code.


Rationale:

More pythonic. At this moment, _('').format() is the way to go, so I 
would need to wrap another call around that: T(_(''), args, 'es_ES') 
<===This is an ugly hack.

# Set the _() function to return the same string

_ = lambda s: s

es = gettext.translation('myapplication', languages=['es_ES'])

def T(translatable_string, args_dictionary = None, language = None)

     if 'es_ES' == language:

         # Return translated, formatted string

         return es.gettext(translatable_string).format(args)


     # Default, return formatted string

     return translatable_string.format(args)




More information about the Python-ideas mailing list