I didn’t make myself clear, sorry. The code example was just to give an initial what I was suggesting. The errors you show demonstrate the example is incomplete. I’d like them to work.
On 24 Jun 2021, at 18:37, Martin (gzlist)
wrote: On Thu, 24 Jun 2021 at 17:25, Eric Nieuwland
wrote: 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)
This isn't quite right as the semantics between f-strings and str.format() are not actually the same (though this isn't well documented):
f'{1 + 2}' '3' str(DelayedFString('{1 + 2}')) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in __str__ KeyError: '1 + 2'
d = dict(a=1) f'{d["a"]}' '1' str(DelayedFString('{d["a"]}')) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in __str__ KeyError: '"a"'
Basically, f-strings rely on eval-like semantics.
Martin