While playing with new f-strings in the recent Python 3.6 release, I've noticed the following:
We create a
foo
variable with valuebar
:>>> foo = 'bar'
Then, we declare a new variable, which is our f-string, and it should take
foo
to be formatted:>>> baz = f'Hanging on in {foo}'
Ok, all going fine and then we call
baz
to check its value:>>> baz 'Hanging on in bar'
Let's try to change the value of
foo
and callbaz
again:>>> foo = 'spam' >>> baz 'Hanging on in bar'
Shouldn't it be dynamic? Why does this happen? I thought the f-string would update if the value of foo
changed, but this didn't happened. I don't understand how this works.
The
f-string
has already been evaluated when you executed:Specifically, it looked up the value for the name
foo
and replaced it with'bar'
, the value that was found for it.baz
then contains the string after it has been formatted.f-string
s aren't constant; meaning, they don't have a replacement field inside them waiting for evaluation after being evaluated. They evaluate when you execute them, after that, the assigned value is just a normal string:For reference, see the section on Formatted String Literals:
After the expression (the look-up for the replacement field and its consequent formatting) is performed, there's nothing special about them, the expression has been evaluated to a string and assigned to
baz
.