On Thu, 24 Jun 2021 at 17:25, Eric Nieuwland <eric.nieuwl...@gmail.com> 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 _______________________________________________ Python-Dev mailing list -- python-dev@python.org To unsubscribe send an email to python-dev-le...@python.org https://mail.python.org/mailman3/lists/python-dev.python.org/ Message archived at https://mail.python.org/archives/list/python-dev@python.org/message/HGITYZPPRXJM4Y7YVJKUSVXUB75W5Z2L/ Code of Conduct: http://python.org/psf/codeofconduct/