3

I'm learning python and when I was reading about formatted string literals, I noticed something in the reference that I cannot understand. Here is the syntax of formatted string literals:

f_string          ::=  (literal_char | "{{" | "}}" | replacement_field)*
replacement_field ::=  "{" f_expression ["="] ["!" conversion] [":" format_spec] "}"
f_expression      ::=  (conditional_expression | "*" or_expr)
                         ("," conditional_expression | "," "*" or_expr)* [","]
                       | yield_expression
conversion        ::=  "s" | "r" | "a"
format_spec       ::=  (literal_char | NULL | replacement_field)*
literal_char      ::=  <any code point except "{", "}" or NULL>

As you see, these are 3 formats for f_expression. The conditional_expression one is easy to understand and here is an example:

a=[1, 2, 3]
print(f'test: {"a" if 4 in a else None}')

But I cannot understand next 2 correctly. First one is "*" or_expr, which means it is an expression that needs to start with *. I cannot write any code that matches this syntax and all codes like:

print(f"test: {(*a)}")

gives me an error which says I cannot use starred expression here. The next one is yield_expression which I somehow get it working like this:

def testit():
    print(f'test: {yield 125}')

for x in testit():
    print(x)

which prints:

125
test: None

I don't understand what is use of this mode inside formatted string literals at all. Can you tell me what is the usage of these 2 expressions in formatted string literals?

Afshin
  • 8,839
  • 1
  • 18
  • 53
  • No answer there but https://bugs.python.org/issue41064 is relevant. – Koterpillar Dec 06 '21 at 06:26
  • 1
    https://stackoverflow.com/questions/19302530/python-generator-send-function-purpose/19302700#19302700 Does this answer your question about the `yield` part? – Koterpillar Dec 06 '21 at 06:33
  • `print(f"test: {(*a,)}")` would have worked – wim Dec 06 '21 at 06:38
  • This is bizarre - a f_expression like `{*a, *b}` works just fine (producing a tuple with the contents of all the iterables), `{*a,}` works too, but not `{*a}`. That grammar simply does not match the actual implementation. – jasonharper Dec 06 '21 at 06:39
  • some discussion about the starred alternative here: https://stackoverflow.com/questions/55933956/what-does-a-star-asterisk-do-in-f-string – ethguo Dec 06 '21 at 06:43
  • @Koterpillar I need to learn more python to understand it, but it seems that one answers the yield part. thanks. – Afshin Dec 06 '21 at 06:49

0 Answers0