On Mon, May 25, 2020 at 06:45:47PM -0400, Eric V. Smith wrote:
> On 5/25/2020 6:37 PM, Chris Angelico wrote:
> >Explicit meaning that you need to use a specific symbol that means
> >"this is to be late-bound"?
> >
> >Or explicit meaning "something that I like", as opposed to implicit
> >meaning "something that I don't like", which is how most people seem
> >to interpret that line of the Zen?
> 
> That's a great comment, and so true. 

We agree on that! But...


> When f-strings were first proposed, 
> people used that exact same line from the Zen to mean "I don't like 
> f-strings". And I was always puzzled: in what way is it not explicit?

Well, there's this: f-strings look like strings. They're called strings. 
People think of them as not just strings but string literals. But 
they're actually executable code that is run at runtime, making them 
semantically an implicit call to `eval`.

    py> print("Actual string: {sum(len(s) for s in dir(builtins))}")
    Actual string: {sum(len(s) for s in dir(builtins))}
    py> print(f"Actual eval: {sum(len(s) for s in dir(builtins))}")
    Actual eval: 1882

The dissassembly of the regular string is two lines, specifically a 
LOAD_CONST and a RETURN_VALUE:

    py> dis.dis(
    ...   compile('"Actual string: {sum(len(s) for s in dir(builtins))}"',
    ...   '', 'eval'))
      1           0 LOAD_CONST               0 ('Actual ...')
                  2 RETURN_VALUE

(I've truncated the value of the constant for brevity.)

The dissassembly of the f-string is twenty-five lines of byte-code, 
including four calls to CALL_FUNCTION.

In my experience, people get defensive when you point this out, and say 
"But it returns a string, so its a string". By that logic, this function 
is a string too:

    lambda: str(sum(len(s) for s in dir(builtins)))

The difference between the f-string and the lambda is that the lambda 
needs explicit parens to perform the computation, the f-string doesn't.

Isn't the whole point of f-strings to iterpolate evaluated expressions 
into a format string without needing an explicit evaluation?

-- 
Steven
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/YADR4SMRJNHVV6QOUDXYADOZBW2GHJXS/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to