import inspectclass 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 rightdef new_scope():names = ["foo", "bar"]for name in names:print(delayed_fstring)new_scope()
f"The current name is {name}" = str(d"The current name is {name}")
What part are you trying to delay, the expression evaluations, or the string building part?
There was a recent discussion on python-ideas starting at https://mail.python.org/archives/list/python...@python.org/message/LYAC7JC5253QISKDLRMUCN27GZVIUWZC/ that might interest you.
Eric
_______________________________________________ Python-Dev mailing list -- pytho...@python.org To unsubscribe send an email to python-d...@python.org https://mail.python.org/mailman3/lists/python-dev.python.org/ Message archived at https://mail.python.org/archives/list/pytho...@python.org/message/GT5DNA7RKRLFWE3V42OTWB7X5ER7KNSL/ Code of Conduct: http://python.org/psf/codeofconduct/
-- Eric V. Smith
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='
On Thu, Jun 24, 2021 at 10:34 AM micro codery <uco...@gmail.com> wrote:
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='
Eric, what would you think of adding this feature to format()? It seems doable (at least for keyword args -- for positional args I don't think it makes sense).
The only problem is that it already has a meaning, as unlikely as it is that someone would use it:
>>> d = {'x = ': 42}
>>> "{x = }".format(**d)
'42'
Plus there's the issue of whitespace being treated differently
with f-strings and str.format().
Honestly, the rest of the discussion belongs on python-ideas.
I totally agree.
Eric