String interpolation is one of those features like inference where if you've had it before then going without is very annoying, and so you add some and that's nicer, then you add more, each step seems like it's an improvement, and then one day you realise you're looking at unintelligible nonsense and you say "Oh no, what have we done?"
This is unusual, often CS would love to have as much of whatever as we can, but mathematics says no that's literally or practically impossible - but here both none and lots are awful and shouldn't be permitted.
One option, which Python and C# both picked is, well, leave it to taste. You can write sixteen pages of layered expressions in the uncommented interpolated string and it'll work, but your colleagues will curse your name and plot your destruction. Or at least you'll fail code review if you enforce such things.
Another option, in standard C++ 23 today for example, is refuse to take even the first step. You can have rich formatting, but standard C++ does not provide interpolation at all, if you want to format six parameters then pass them as parameters.
I'm happy with Rust's "Only a tiny bit of interpolation" where you can interpolate only identifiers, not any other expressions, but that's definitely more interpolation than some will be happy with, yet of course in some cases it's not quite enough.
Purity and practicality are at odds and every language finds a different balance between the two. There is no one correct balance so busy minds will inevitably have loud opinions they want accepted as the one correct balance.
> then you add more, each step seems like it's an improvement, and then one day you realise you're looking at unintelligible nonsense and you say "Oh no, what have we done?"
I've never found it difficult to keep them in check. I still can't fathom a use case for nesting f-strings within an f-string substitution, for example. And probably the only format specifier I commonly use is `:02x`.
I hate Rust's solution because it's not a solution at all.
Interpolation only works in a small subset of cases, which makes you constantly having to think whether it can or can't be used in the current situation and requires endless churn when refactoring code.
At the very minimum, they need to allow it to work with field access.
On the other hand, in python, while examples like this site exist and are funny/weird/quirky in practice nobody cares, and they just enjoy using fstrings.
It's pretty straightforward? You can interpolate a variable in scope and apply modifiers to it. You can't interpolate arbitrary expressions (which field access would be). Alternatively, you can interpolate an arbitrary identifier, then specify a value for that identifier in the arguments.
Take optimisation, another task like interpolation which the machine does to transform our program text into an executable
We'd like exhaustive optimisation, in fact that can't be done and today we're used to a relatively aggressive optimisation which would not have been possible fifty years ago, but we're nowhere close to optimal for non-trivial programs.
Or correctness, it seems as though global static analysis should be possible, at least for something modest like a typical Unix utility - nope, that is known to be mathematically impossible for even quite modest software, only local analysis is at least plausible and its effects are much more limited than we might hope.
I, too, struggled to understand the meaning of this sentence. I can parse it, I guess, but any meaning I try to guess for it is either implausible or irrelevant.
Learned a few tricks that I'm sure are buried on fstring.help somewhere (^ for centering, # for 0x/0b/0o prefixes, !a for ascii). I missed the nested f-strings question, because I've been stuck with 3.11 rules, where nested f-strings are still allowed but require different quote characters (e.g. print(f"{f'{{}}'}") would work). I guess this got cleaned up (along with a bunch of other restrictions like backslashes and newlines) in 3.12.
F-strings are great, but trying to remember the minute differences between string interpolation, old-style formatting with %, and new-style formatting with .format(), is sort of a headache, and there's cases where it's unavoidable to switch between them with some regularity (custom __format__ methods, templating strings, logging, etc). It's great that there's ergonomic new ways of doing things, which makes it all the more frustrating to regularly have to revert to older, less polished solutions.
One thing I keep not understanding is I see colleagues or AIs put f-strings in logger calls! Doesn't the logger do lazy interpolation? Doesn't this lose that nice feature?
Yeah I consider that one to be a trick question. I knew same-quote-style nested f-strings were coming, I just didn't know which version, and I still use the `f'{f"{}"}'` trick because I want my code to support "older" versions of python. One of my servers is still on 3.10. 3.11 won't be EOL until 2027.
If you come from verbosity land C# release notes are magically good as well, always some way to reduce boilerplate while maintaining "implicit verbosity" which your proprietary LSP resolves 100% correctly.
I'd prefer writing C# if I had the Linux interaction libs Python has. I'm too dumb to write syscall wrappers
It makes me sad that the PEP for the equivalent behaviour for function keyword arguments wasn’t accepted. It’s really common to see foo(bar=bar) and I think it’s not only cleaner but would help see subtle differences if that was foo(bar=) because it would make the cases where some arguments aren’t simply being passed through more obvious: foo(bar=, …, baaz=baaz.get_id()) avoids the most interesting detail being easily missed.
Do you know why? I didn't know of the fstring one either but I've thought to myself across many languages that a way to print the expression (or just varname in my head) with the result should exist.
Grammar changes, in particular things used everywhere like function invocations, have to be worth paying the price for changing/adding new rules. The benefits of fewer characters and more explicit intention weren't enough to outweigh the costs.
There were other considerations: Do linters prefer one syntax to another? Does the name refer to the parameter or the argument in tooling? Should users feel pressure to name local variables the same as the function's parameters? What about more shorthand for common cases like func(x=self.x, y=self.y)?
I personally did not like the func(x=, y=) syntax. I think their example of Ruby's func(x:, y:) would actually make more sense, since it's syntax that would read less like "x equals nothing", and more "this is special syntax for passing arguments".
Guess I will chime in for the dissent: there is already so much Python language. The more special gotchas that are added just for these minor wins is not worth it. In fact, if I ever saw a function that was foo(bar=) I would correct that to be explicit immediately. ‘import this’ and all that.
Said as a curmudgeon that has never used a walrus.
And it seems like a bad idea because of that wow factor - it isn't really adding enough to justify having surprising behaviour. It is more likely to be a bug than a feature.
It'd be better to just let people implement their own function that prints a subset of locals(), or provide a standard function that does the same.
Incredibly common for debug output. In C++, I have made it a habit to just copy the expression, once with quotes and once without. It's informative and doesn't require thinking, or, well, I'm still working on that.
You can pry the walrus operator from my cold dead hands.
m = re.match(pattern1, line)
if m:
do_stuff(m.group(1))
else:
m = re.match(pattern2, line)
if m:
do_other_stuff(m.group(2))
else:
m = re.match(pattern3, line)
if m:
do_things(m.groups())
else:
m = ...
Obviously, there are ways to improve this particular example without using the walrus. But it's also usually not this simple.
I run into something like this allthetime. Not many times per program, and I don't actually use the walrus all that often, but when it's the right thing it's so very nice.
I think the feature bloat here has passed the break-even point where no one person needs all this, and it takes so long to find what you need in the docs, and you can't be expected to memorize it, because it's so rare to need to use it, and you can't reliably reverse-search the esoteric syntax you encounter, that any given dev is going to take the path of least resistance and write their own routines for this stuff.
Pad left? That's a two-line method at most. Versus trying to remember whether the syntax is x:n< or x:<n or what. It's faster to do it yourself ad-hoc. And if the next dev has a question about how it works, the implementation is right there (and easy to customize!) not buried in the docs and immutable.
I'd take the middle road, provide a pad_left/pad_right function or method with keyword arguments for specifying things like the padding character. With how often I need to pad some string (often but not every day), this would be my favourite solution.
The standard library having no solution of its own is how you end up with JavaScript and every project reimplementing their 10% of a proper standard library, only slower and with more bugs.
Though I won't probably use Python's </>/^ format modifiers in my project, I could maybe see them working out in some software that frequently outputs "monospaced" text. In a particular niche, what we think of a needless character-pinching might be seen as a crucial feature and used daily.
I find that weird stuff is often used a lot in a single code base, or it’s not used at all. Solve it once, and copy/paste it every other time you need it in the future.
As someone who hasn't written Python in anger since before f-strings were a thing, I correctly guessed almost all the f-string specific syntax but made a bunch of errors that were just to do with the return values of various expressions. Maybe f-strings are the least wtf thing about Python? :)
I don't really think there's anything "wtf" worthy about this. A lot of it isn't even about f-string behavior but about the "mini-language" for str.format()
Right, I assumed the real point the quiz was making is that Python is as full of footguns as JavaScript, since I've seen this type of thing for JS a bunch of times.
Not saying I agree, but was definitely expecting that to be the main topic of discussion here...
More specific shenanigans aside, JavaScript will always be the king of unintuitive syntax. Some of these f-string tidbits are very much strange, but you'd have to be implementing something specific to encounter them. Meanwhile over in JS you're still waiting for your dependencies to install so you can compare two arrays.
That is exactly the kind of unfounded, strawman-riddled criticism I was after ;-)
What does an algorithmic task such as array comparison have to do with language syntax? The answer is nothing.
Sure, some languages might have builtins for comparing certain things, or doing intersections/differences, but those only apply to arrays of primitives, and even in those cases the utility of the builtins completely depends on the use case, and those builtins still have nothing to do with syntax.
let template = 'hello ${name}';
let n1 = template.format({ 'name':'joe' });
let n2 = template.format({ 'name':'bob' });
I am not really a javascript programmer. but I was writing some and wanted to store a bunch of templates then fill them out dynamically and was unable to figure out how to do it with the native javascript template system. So I ended up having to write my own. As it appears to be a huge obvious hole in missing functionality, I have to ask. Am I holding it wrong?
While writing this up I was rereading the mdn page on template literals, perhaps tagged templates would do what I wanted, I don't remember why I did not use them(I think it is still not possible to store the template), but on first glance, yeah, lamentations about the unintuitive syntax and weird features.
(Tagged templates won’t help here because the bit in curly braces is an expression which is evaluated to a value first; you’d need some kind of macro system to get access to the original variable name at runtime.)
I like this quiz format much more than just reading a doc because I get to guess what it might do before finding out, which reinforces how well I remember it. As a Python amateur I had no idea fstrings were so powerful!
Oh am I writing python code for some years this should be fun ... oh. Oh I see. Hmm. Ok, just give it to me: are they turing complete yet or do we need to wait for 3.14?
21/26, with a couple of sleep-deprived brainfarts and a misclick. Learned very little, although I had the wrong reasoning for one of the ones I got right (tested afterward). I don't even use the {var=} thing or walrus operator, though.
I would definitely not do nearly as well on jsdate.wtf. I really still think JS has the greater WTFs.
I was not sure about the difficulty. Python has some really weird behaviors with some of the custom __format__. For instance f"{'None':<010}" will pad out, but f"{None:<010}" will error. The only one I ended up putting in is the gotcha that bool is an int subclass and gets the int behavior for custom format parameters (which almost sounds like a bug). f'{''''''''''''}' is also a weird one, but that is mostly an issue with the string concatenation syntax and not fstrings :)
There definitely are some more odd / confusing ones.
Ah I see, fair enough I suppose. Quite nice for catching bugs though to be honest - since you'll hit an error and realise you need to handle the None case appropriately, rather than a more subtle 'None' appearing somewhere bug.
I got 20/26. Only ones that really got me were walrus syntax collisions, the types with weirder padding behaviour, some format specifiers I wasn't familiar with. A lot of these are more trivia than wtfs, but not a bad quiz.
> why python needs N built-in ways to [do something where there should ideally be only one obvious way]
It's the same every time: because some people are unsatisfied with the existing ways and want new ones added, but other people will rain fire and brimstone if you remove the old ones.
(BTW: the exact — non-obvious — way the dashes are placed for that line of the Zen is apparently a deliberate joke.)
> many recent Python extensions seem features in search of use cases […] The real problem with Python, of course, is that its evolution is largely driven by narcissism, not user feedback.
I'm surprised to find that there're so many feature of f-string that I've never heard of. I don't think I'm gonna use them any time soon but nice to know about that.
As someone who works on a codebase with almost no comments, please leave a comment for every block of code that does something and explain why (1 comment for every 5 or 10 lines of code should be fine).
the reward for 100% should be a directory of languages that deals with strings in a sane/singular/readable way.
it's cool that half of those features are there. it's not cool that half the devs that read the thing after creation are going to have to look up the f string features.
T-strings use the exact same syntax as f‑strings, but their “format spec” (the part after the optional :, like .2f) can effectively be anything.
That might make creating a quiz tricky? With f‑strings, Python immediately calls format() on that spec; with t‑strings, it's simply captured in Interpolation.format_spec. It's up to your code to decide whether to call format() or do something entirely different with this value.
This is unusual, often CS would love to have as much of whatever as we can, but mathematics says no that's literally or practically impossible - but here both none and lots are awful and shouldn't be permitted.
One option, which Python and C# both picked is, well, leave it to taste. You can write sixteen pages of layered expressions in the uncommented interpolated string and it'll work, but your colleagues will curse your name and plot your destruction. Or at least you'll fail code review if you enforce such things.
Another option, in standard C++ 23 today for example, is refuse to take even the first step. You can have rich formatting, but standard C++ does not provide interpolation at all, if you want to format six parameters then pass them as parameters.
I'm happy with Rust's "Only a tiny bit of interpolation" where you can interpolate only identifiers, not any other expressions, but that's definitely more interpolation than some will be happy with, yet of course in some cases it's not quite enough.
cute pun but compared to busybodies it really hides the implication (i thought you were talking about people with adhd at first).
Every time I need to format a number or a date in C#, I just hit the documentation. I refuse to memorize its terrible formatting mini language.
I've never found it difficult to keep them in check. I still can't fathom a use case for nesting f-strings within an f-string substitution, for example. And probably the only format specifier I commonly use is `:02x`.
Interpolation only works in a small subset of cases, which makes you constantly having to think whether it can or can't be used in the current situation and requires endless churn when refactoring code.
At the very minimum, they need to allow it to work with field access.
On the other hand, in python, while examples like this site exist and are funny/weird/quirky in practice nobody cares, and they just enjoy using fstrings.
The key is "identifiers, not expressions."
What does this have to do with either topic?
We'd like exhaustive optimisation, in fact that can't be done and today we're used to a relatively aggressive optimisation which would not have been possible fifty years ago, but we're nowhere close to optimal for non-trivial programs.
Or correctness, it seems as though global static analysis should be possible, at least for something modest like a typical Unix utility - nope, that is known to be mathematically impossible for even quite modest software, only local analysis is at least plausible and its effects are much more limited than we might hope.
70% of these "wtfs" aren't about string interpolation but just python's syntax for string.format
https://docs.python.org/3/library/string.html#format-string-...
F-strings are great, but trying to remember the minute differences between string interpolation, old-style formatting with %, and new-style formatting with .format(), is sort of a headache, and there's cases where it's unavoidable to switch between them with some regularity (custom __format__ methods, templating strings, logging, etc). It's great that there's ergonomic new ways of doing things, which makes it all the more frustrating to regularly have to revert to older, less polished solutions.
Yes: https://docs.python.org/3/whatsnew/3.12.html#whatsnew312-pep...
The = support was added in Python 3.8: https://docs.python.org/3/whatsnew/3.8.html#f-strings-suppor...
I'd prefer writing C# if I had the Linux interaction libs Python has. I'm too dumb to write syscall wrappers
The discussion: https://discuss.python.org/t/pep-736-keyword-argument-shorth...
The rejection: https://discuss.python.org/t/pep-736-shorthand-syntax-for-ke...
Grammar changes, in particular things used everywhere like function invocations, have to be worth paying the price for changing/adding new rules. The benefits of fewer characters and more explicit intention weren't enough to outweigh the costs.
There were other considerations: Do linters prefer one syntax to another? Does the name refer to the parameter or the argument in tooling? Should users feel pressure to name local variables the same as the function's parameters? What about more shorthand for common cases like func(x=self.x, y=self.y)?
I personally did not like the func(x=, y=) syntax. I think their example of Ruby's func(x:, y:) would actually make more sense, since it's syntax that would read less like "x equals nothing", and more "this is special syntax for passing arguments".
Said as a curmudgeon that has never used a walrus.
It'd be better to just let people implement their own function that prints a subset of locals(), or provide a standard function that does the same.
print("foo", foo)
I run into something like this all the time. Not many times per program, and I don't actually use the walrus all that often, but when it's the right thing it's so very nice.
I feel the same way with rust control flow being used as an expression, and am disappointed when other languages don’t have it.
Even though one could argue it makes things more complicated, I feel more mental freedom and feel the language getting out of the way.
The assignment is the least problematic thing on that code. I do even disagree on it being a problem.
Edit: someone downvoted me because they don't understand there is no walrus operator here
Pad left? That's a two-line method at most. Versus trying to remember whether the syntax is x:n< or x:<n or what. It's faster to do it yourself ad-hoc. And if the next dev has a question about how it works, the implementation is right there (and easy to customize!) not buried in the docs and immutable.
The functionality comes from the prior string.format method, which has been around since Python 2.6 (first released in 2008).
https://docs.python.org/2.6/library/string.html#formatspec
> It's faster to do it yourself ad-hoc.
I have found the syntax to be quite mentally "sticky".
> the implementation is right there (and easy to customize!) not buried in the docs and immutable.
There are hooks to customize it.
The standard library having no solution of its own is how you end up with JavaScript and every project reimplementing their 10% of a proper standard library, only slower and with more bugs.
Though I won't probably use Python's </>/^ format modifiers in my project, I could maybe see them working out in some software that frequently outputs "monospaced" text. In a particular niche, what we think of a needless character-pinching might be seen as a crucial feature and used daily.
Glad this is nowhere near Wat [2], though.
[1]: https://ezhik.jp/f-string.lua/
[2]: https://www.destroyallsoftware.com/talks/wat
Not saying I agree, but was definitely expecting that to be the main topic of discussion here...
What does an algorithmic task such as array comparison have to do with language syntax? The answer is nothing.
Sure, some languages might have builtins for comparing certain things, or doing intersections/differences, but those only apply to arrays of primitives, and even in those cases the utility of the builtins completely depends on the use case, and those builtins still have nothing to do with syntax.
Do they really not support the equivalent to
I am not really a javascript programmer. but I was writing some and wanted to store a bunch of templates then fill them out dynamically and was unable to figure out how to do it with the native javascript template system. So I ended up having to write my own. As it appears to be a huge obvious hole in missing functionality, I have to ask. Am I holding it wrong?While writing this up I was rereading the mdn page on template literals, perhaps tagged templates would do what I wanted, I don't remember why I did not use them(I think it is still not possible to store the template), but on first glance, yeah, lamentations about the unintuitive syntax and weird features.
Hell is paved with good will I guess. Probably Justine should update https://justine.lol/lex/
C'mon, every language has quirks.
[1] https://www.destroyallsoftware.com/talks/wat
I have so much Python to learn, I scored 10/26
I would definitely not do nearly as well on jsdate.wtf. I really still think JS has the greater WTFs.
There definitely are some more odd / confusing ones.
Is that any different than being surprised that 1 + 1 is 2 and '1' + '1' is '11'?
It's the same every time: because some people are unsatisfied with the existing ways and want new ones added, but other people will rain fire and brimstone if you remove the old ones.
(BTW: the exact — non-obvious — way the dashes are placed for that line of the Zen is apparently a deliberate joke.)
Mark Lutz
https://learning-python.com/python-changes-2014-plus.html
Let's not psychoanalyze Guido
I'm surprised to find that there're so many feature of f-string that I've never heard of. I don't think I'm gonna use them any time soon but nice to know about that.
And is there a way to link to a specific question?
https://docs.python.org/3/library/operator.html#mapping-oper...
I always use a reference when doing anything non-trivial with format strings of any kind and this quiz confirmed I should keep doing that.
Also I've been using Python professionally for over a decade but TIL about the Ellipsis object.
And for regex you have this in some languages: https://docs.python.org/3/library/re.html#re.X
it's cool that half of those features are there. it's not cool that half the devs that read the thing after creation are going to have to look up the f string features.
T-strings use the exact same syntax as f‑strings, but their “format spec” (the part after the optional :, like .2f) can effectively be anything.
That might make creating a quiz tricky? With f‑strings, Python immediately calls format() on that spec; with t‑strings, it's simply captured in Interpolation.format_spec. It's up to your code to decide whether to call format() or do something entirely different with this value.