[Python-ideas] String interpolation for all literal strings

Yury Selivanov yselivanov.ml at gmail.com
Fri Aug 7 00:21:07 CEST 2015


Barry,

On 2015-08-06 5:53 PM, Barry Warsaw wrote:
> On Aug 06, 2015, at 03:37 PM, Yury Selivanov wrote:
>
>> What if we introduce f-strings in the following fashion:
>>
>> 1. ``f'string {var}'`` is equivalent to
>> ``'string {var}'.format(**locals())`` -- no new formatting
>> syntax.
> You really do want to include globals too, with locals overriding them.

Right, I should have written 'format(**globals(), **locals())',
but in reality I hope we can make compile.c to inline vars
statically.

>> 2. there is a 'sys.set_format_hook()' function that allows
>> to set a global formatting hook for all f-strings:
>>
>>      # pseudo-code
>>      def i18n(str, vars):
>>          if current_lang != 'en':
>>              str = gettext(str, current_lang)
>>          return str.format(vars)
>>
>>      sys.set_format_hook(i18n)
>>
>> This would allow much more convenient way not only to format
>> strings, but also to integrate various i18n frameworks:
>>
>>     f'Welcome, {user}' instead of _('Welcome, {user}')
> I don't think you want this to be a process-global hook since different
> modules may be using a different i18n systems.

I agree this might be an issue.  Not sure how widespread the
practice of using multiple systems in one project is, though.

Just some ideas off the top of my head on how this can be
tackled (this is an off-topic for this thread, but it might
result in something interesting):

- we can have a convention of setting/unsetting the global
callback per http request / rendering block / etc

- we can pass the full module name (or module object) to the
callback as an extra argument; this way it's possible to
design a mechanism to "target" different i18n frameworks for
different "parts" of the application

- the idea can be extended to provide a more elaborate and
standardized i18n API, so that different systems use it and
can co-exist without conflicting with each other

- during rendering of an f-string we can check if globals() have
a '__format_hook__' name defined in it; this way it's possible
to have a per-module i18n system

Anyways, it would be nice if we can make i18n a little bit
easier and standardized in python.  That would help with
adding i18n in existing projects, that weren't designed with
it in mind from start.

Yury


More information about the Python-ideas mailing list