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-id...@python.org/message/LYAC7JC5253QISKDLRMUCN27GZVIUWZC/ that might interest you.

Eric

On 6/24/2021 5:37 AM, 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-evaluation-of-f-strings <https://stackoverflow.com/questions/42497625/how-to-postpone-defer-the-evaluation-of-f-strings> 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-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/GT5DNA7RKRLFWE3V42OTWB7X5ER7KNSL/
Code of Conduct: http://python.org/psf/codeofconduct/

--
Eric V. Smith

_______________________________________________
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/O4D36DQEZU5SBIAMN227NQAR3FSVVOXR/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to