As pointed out already, f-strings and format are subtly different (not counting that one can eval and the other cannot). Besides quoting, the f-sting mini language has diverged from format's
spam="Spam" f"{spam=}" "spam='Spam'" "{spam=}".format(spam=spam) Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'spam='
I created a package some time ago to do exactly this
https://pypi.org/project/f-yeah/
On Thu, Jun 24, 2021 at 10:07 AM Luciano Ramalho
I don't think that would be a good idea since we already have .format() which covers that use case and is more flexible than f-strings (it supports positional arguments, as well as *args and **kwargs).
I think keeping f-strings simple is a better idea.
Best,
Luciano
On Thu, Jun 24, 2021 at 1:30 PM Eric Nieuwland
wrote: 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 ‘%’.
I found
https://stackoverflow.com/questions/42497625/how-to-postpone-defer-the-evalu... and tweaked it a bit to:
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.
_______________________________________________ Python-Dev mailing list -- python-dev@python.org To unsubscribe send an email to python-dev-leave@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/GT5DNA7R...
Code of Conduct: http://python.org/psf/codeofconduct/
-- Luciano Ramalho | Author of Fluent Python (O'Reilly, 2015) | http://shop.oreilly.com/product/0636920032519.do | Technical Principal at ThoughtWorks | Twitter: @ramalhoorg _______________________________________________ Python-Dev mailing list -- python-dev@python.org To unsubscribe send an email to python-dev-leave@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/LVPDNGUR... Code of Conduct: http://python.org/psf/codeofconduct/