![](https://secure.gravatar.com/avatar/5615a372d9866f203a22b2c437527bbb.jpg?s=120&d=mm&r=g)
On Wed, Oct 21, 2020 at 02:15:40AM +1100, Chris Angelico wrote:
On Tue, Oct 20, 2020 at 11:54 PM Steven D'Aprano <steve@pearwood.info> wrote:
The only advantage, I guess, of f-string like syntax is that the variable names can be embedded inside the template string:
f"{path:s} - {errors:d} errors, {%warnings:d}" = line
but I'm not convinced that's actually an advantage. I think I prefer the C-style for this.
It's exactly the same advantage that they have as rvalues, and I think there's more to be said for it than is obvious at first glance. Consider that patterns might not be nice tidy things like this; they might be parsing an obscure sequence of tokens (because, let's face it, a lot of text out there isn't designed well), so your pattern might be something like:
f"{path}: {errors:d}/{warnings:d}" = line
*scratches head* I'm not seeing that this is a more obscure or complex example. It looks like you have just changed the format from: path - 123 errors, 456 warnings to path: 123/456
or even:
f"{acc},{date},{type},{amount:[0-9.]} {description},{refnum:12s}{reference}" = line
At the point you have something that complicated, I think that existing solutions with regexes or parsers is better. Overloading something that looks like an f-string with a mini-language that is way more complicated than the mini-language used in actual f-strings is, I think, a losing proposition.
- As others have mentioned: could inject variables into locals() making debugging harder.
I'm dubious about that too. I think it would be better to keep the parsing separate from the name binding, and use regular assignment for that.
Not sure what the concern with "inject[ing] variables" is.
What you see as a feature, some of us see as a problem: the fact that *some* variables will be updated even if the pattern doesn't match. So if you have a pattern that doesn't match the given string, it could still have side-effects of creating or over-writing local variables.
The f-string has to be a literal - it's not a magic object that you can assign to and new locals appear.
Well, no, it's not an object at all, but surely "you can assign to and new locals appear" is the whole point of the feature? You assign to the f-string and it matches values from the string on the right hand side to create new locals, or over-write existing ones. f"{name}: {value:d}" = "eleventytwo: 112" will have the side effect of binding: name = "eleventytwo" value = 112 -- Steve