Is there a callable equivalent to f-string syntax?
Brief answer: NO.
You can read PEP-498 regarding these f-strings. It clearly defines their purpose, and the concept: these strings are evaluated in-place. The result is a usual str
with formatted content. You cannot store f-strings as a template, as there is no special object for f-strings.
Your specific example is also mentioned in PEP-498's "Differences between f-string and str.format expressions" section.
So, whatever you do, you either use the inline in-place f-strings, or the old s.format()
syntax, with different behaviour.
If you want to read an f-string from a file and evaluate it according to the syntax of f-strings, you could use eval:
foo = {'blah': 'bang', 'bar': 'sorry'}
bar = 'blah'
tpl = '{foo[bar]}'
print(tpl)
print(tpl.format(**locals())) # sorry
print(eval(f'f{tpl!r}')) # bang
Note how we use the f-string first, but convert the tpl
into its own repr for immediate eval. Typically, for simple types, eval(repr(val))
should return val
. But instead of just putting repr(tpl)
(or {tpl!r}
), we convert the repr of the regular string into the f-string, and evaluate it instead.