[Python-checkins] peps: Added a section on the same expression being used multiple times in the same

eric.smith python-checkins at python.org
Sat Aug 29 03:45:15 CEST 2015


https://hg.python.org/peps/rev/9af8765a7661
changeset:   6006:9af8765a7661
user:        Eric V. Smith <eric at trueblade.com>
date:        Fri Aug 28 21:43:48 2015 -0400
summary:
  Added a section on the same expression being used multiple times in the same f-string.

files:
  pep-0498.txt |  41 +++++++++++++++++++++++++++++++++++++--
  1 files changed, 38 insertions(+), 3 deletions(-)


diff --git a/pep-0498.txt b/pep-0498.txt
--- a/pep-0498.txt
+++ b/pep-0498.txt
@@ -640,10 +640,45 @@
 
   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
 ==========

-- 
Repository URL: https://hg.python.org/peps


More information about the Python-checkins mailing list