From 617e3748a8d1105108db4accc03b32476b7482b4 Mon Sep 17 00:00:00 2001 From: "Eric V. Smith" Date: Fri, 28 Aug 2015 21:43:48 -0400 Subject: [PATCH] Added a section on the same expression being used multiple times in the same f-string. --- pep-0498.txt | 41 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/pep-0498.txt b/pep-0498.txt index 836ca77bf..c29e6d913 100644 --- a/pep-0498.txt +++ b/pep-0498.txt @@ -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 ==========