Why don't f-strings change when the variables they refer to change?

While playing with new f-lines in a recent version of Python 3.6, I noticed the following:

  • Create a variable foo with the value bar :

     >>> foo = 'bar' 
  • Then we declare a new variable, which is our f-string, and it should format foo :

     >>> baz = f'Hanging on in {foo}' 
  • Ok, everything goes well, and then we call baz to check its value:

     >>> baz 'Hanging on in bar' 
  • Try changing the value of foo and calling baz again:

     >>> foo = 'spam' >>> baz 'Hanging on in bar' 

Isn't that a speaker? Why is this happening? I thought that the f-line would be updated if the value of foo changed, but this did not happen. I do not understand how this works.

+8
python f-string
source share
2 answers

f-string has already been evaluated on execution:

 >>> baz = f'Hanging on in {foo}' 

In particular, he looked up the value for the name foo and replaced it with 'bar' , the value that was found for him. baz then contains the string after formatting it.

f-string are not constant; that is, they don’t have a replacement field inside waiting for evaluation after evaluation. They evaluate when you execute them, after which the assigned value is a normal string:

 >>> type(f'hanging on in {foo}') <class 'str'> 

For help, see the section on formatted string literals :

[..] While other string literals always have a constant value, formatted strings are indeed expressions evaluated at runtime. [..]

After the expression is executed (search for the replacement field and its subsequent formatting), there is nothing special in them, the expression was evaluated in a string and assigned to baz .

+13
source share

Strings are immutable, and after creating a string, it can no longer be changed.

foo and, more importantly, baz are both lines. This means that when they are created, they fall into memory and can no longer be changed.

Once you assigned foo = bar , you created this object and assigned it to a specific location in memory. The same thing was done with baz .

Even if baz was like a string literal format , it does not mean that it is no longer immutable, because:

 In [4]: type(baz) Out[4]: str 

Thus, baz was created as an object and assigned to your memory as Hanging on in bar , so its relation to foo is pure during instance creation. During which baz searches for the foo object and concatenates it when necessary.

Once you created foo = 'spam' , you destroyed the original destination foo and created a new one in memory.

0
source share

All Articles