I found this example on the internet
def format_attributes(**attributes):
"""Return a string of comma-separated key-value pairs."""
return ", ".join(
f"{param}: {value}"
for param, value in attributes.items()
)
The syntax of the param passed to the join
function caught my attention because it's sort of unusual. But it works
Doing some local testing with a minimum codebase I discovered that in:
def foo(res):
return res
print(foo(f"{s}" for s in ["bar"]))
foo's
syntax is valid and res
ends up being a generator. However, if I try f"{s}" for s in ["bar"]
standalone (no function in between), the expression just throws a SyntaxError: invalid syntax
.
How come the f-string
+ for loop
is valid and gets converted into a generator
? What's happening under the hood when invoking foo
function?
These other questions uses the same syntax:
- f-strings formatter including for-loop or if conditions
- https://stackoverflow.com/a/54734702/5745962
But I found no comment explaining why this happens