Added a section on the same expression being used multiple times in the same f-string.

This commit is contained in:
Eric V. Smith 2015-08-28 21:43:48 -04:00
parent 5d0b58c678
commit 617e3748a8
1 changed files with 38 additions and 3 deletions

View File

@ -640,10 +640,45 @@ having 2 expressions::
f'{x:.{width}}'
Expressions used multiple times
-------------------------------
The same expression used multiple times
---------------------------------------
xxx
Every expression in braces in an f-string is evaluated exactly
once. If the same expression is used more than once in the same
f-string, it will be evaluated multiple times. However, it's undefined
which result will show up in the resulting string value. For purposes
of this section, two expressions are the same if they have the exact
same literal text defining them. For example, '{i}' and '{i}' are the
same expression, but '{i}' and '{ i}' are not, due to the extra space
in the second expression.
For example, given::
>>> def fn(lst):
... lst[0] += 1
... return lst[0]
...
>>> lst=[0]
>>> f'{fn(lst)} {fn(lst)}'
'1 2'
The resulting f-string might have the value '1 2', '2 2', '1 1', or
even '2 1'.
However::
>>> lst=[0]
>>> f'{fn(lst)} { fn(lst)}'
'1 2'
This f-string will always have the value '1 2'. This is due to the two
expressions not being the same: the space in the second example makes
the two expressions distinct.
This restriction is in place in order to allow for a possible future
extension allowing translated strings, wherein the expression
substitutions would be identified by their text values as they show up
between the braces.
References
==========