Everybody loves Python 3.6's new f-strings:
In [33]: foo = {'blah': 'bang'}In [34]: bar = 'blah'In [35]: f'{foo[bar]}'
Out[35]: 'bang'
However, while functionally very similar, they don't have the exact same semantics as str.format()
:
In [36]: '{foo[bar]}'.format(**locals())
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-36-b7ef5aead76c> in <module>()
----> 1 '{foo[bar]}'.format(**locals())KeyError: 'bar'
In particular, str.format()
handles getitem syntax very differently:
In [39]: '{foo[blah]}'.format(**locals())
Out[39]: 'bang'
Given the ability to handle full-blown python expression syntax, f-strings are wonderful and I love them. But they have one hitch: they're evaluated immediately, whereas with str.format()
I can save the string with its formatting as a template, and format it multiple times in different contexts.
So, is there an equivalent way to save a string as a template, and evaluate it, using f-string semantics, at a later date? Other than defining a function? Is there an equivalent to str.format()
for f-strings?
Update:
So, hypothetical interface here as an example:
In [40]: mystr = '{foo[bar]}'In [41]: make_mine_fstring(mystr, foo=foo, bar=bar)
Out[41]: 'bang'