[Python-ideas] Draft PEP on string interpolation
Ron Adam
ron3200 at gmail.com
Thu Aug 27 03:08:55 CEST 2015
On 08/26/2015 10:39 AM, Eric V. Smith wrote:
> On 08/26/2015 11:06 AM, Eric V. Smith wrote:
>> >On 08/26/2015 10:51 AM, Ron Adam wrote:
>>> >>I don't have time to test yours this morning, but What happens in this
>>> >>case?
>>> >>
>>> >> x = [1]
>>> >> ix = i('{x}')
>>> >> x = [2] # Mutates i-string content?
Oops on my part... I should have written what you did below to mutate x
and not rebind it.
>>> >> print(str(ix))
>>> >>
>>> >>Does this print "[1]" or "[2]"?
>> >
>> >I added a similar test this morning. My code produces "[2]". I can't
>> >imagine a design that could produce a different result, but follow the
>> >"delayed evaluation of the string" model.
> Oops, I misread this as mutating x. Mine would produce "[1]". Here are
> the tests:
Ok... I see, but you understood the direction I was going...
> # changing a mutable value doesn't affect the i-string
> n = 0
> x = i('{n}')
> self.assertEqual(str(x), '0')
> n = 1
> self.assertEqual(str(x), '0')
Yes, changing the name reference, which isn't the same as changing a
mutable, doesn't change the object in the i-string. That's already
evaluated in the __init__ method.
> # but a mutable value will
> l = [1]
> x = i('{l}')
> self.assertEqual(str(x), '[1]')
> l[0] = 2
> self.assertEqual(str(x), '[2]')
This was the example I was meaning to write above.. which you figured
out. ;-) And you get '[2]'.
If you store a string instead of the value, then mutating the object
won't effect the i-string. Also you don't get held references to
objects that may be more expensive than a string.
I think these points need to be in the PEP.
Cheers,
Ron
More information about the Python-ideas
mailing list