In a recent discussion with a colleague we wondered if it would be possible to postpone the evaluation of an f-string so we could use it like a regular string and .format() or ‘%’.
import inspect
class DelayedFString(str):
def __str__(self):
vars = inspect.currentframe().f_back.f_globals.copy()
vars.update(inspect.currentframe().f_back.f_locals)
return self.format(**vars)
delayed_fstring = DelayedFString("The current name is {name}")
# use it inside a function to demonstrate it gets the scoping right
def new_scope():
names = ["foo", "bar"]
for name in names:
print(delayed_fstring)
new_scope()
While this does what it should it is very slow.
So I wondered whether it would be an idea to introduce d-strings (delayed f-strings) and make f-strings syntactic sugar for
f"The current name is {name}" = str(d"The current name is {name}")
And perhaps access to the variables and conversions specified in the d-string.