24.06.21 12:37, Eric Nieuwland пише: > 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 ‘%’.
You can just use lambda: delayed_fstring = lambda: f"The current name is {name}" print(delayed_fstring()) If you want to get rid of () when convert to string, you can use a wrapper: class LazyStr: def __init__(self, str_func): self._str_func = str_func def __str__(self): return self._str_func() delayed_fstring = LazyStr(lambda: f"The current name is {name}") print(delayed_fstring) but it works only if str() is directly or indirectly called for the value. You cannot pass it open() as a file name, because open() expects only str, bytes, integer of path-like object. Most builtin functions will not and could not work with LazyStr. As for evaluating variables in different scope as in your example, it just does not work in Python. Python uses static binding, not dynamic binding. First than introducing "delayed f-strings" you need to introduce dynamic binding in normal functions. _______________________________________________ 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/IG6HEHUXY3K4WJ2PYIG47II7ESOIAQIK/ Code of Conduct: http://python.org/psf/codeofconduct/