On Wed, Oct 21, 2020 at 02:18:49AM +1100, Chris Angelico wrote:
Er, well, why not just add a sscanf to Python?
A couple of reasons, but the main one is that you can't have "output variables" (in C, sscanf takes pointers, so you pass it the address of your variables), which means that all you'd get is a fancy string split and then you put all the assignment on the left.
That sounds like a big PLUS to me :-) A fancy string split is precisely what I want. The less magic the better.
That leads to an all-or-nothing result for the simple form, and no easy way to do anything else. Consider:
a, b, c = sscanf("%d %d %d", "123 432")
Boom! Instead of having a clean way to represent partial parsing.
Okay, let's try "partial parsing" with an f-string style: f"{spam:d} {eggs:d} {cheese:d}" = "123 456" Now what? How do you use this in practice? try: spam except NameError: print("no match!") else: try: eggs except NameError: print("Matched spam only") else: try: cheese except NameError: print("Matches spam and eggs only") else: process(spam, eggs, cheese) Gag me with a spoon. In general, Python bindings are *all or nothing* -- either all the targets get bound, or none of them. You may be able to find some odd corner case where this is not true, but the most common case is all-or-nothing: spam, eggs, cheese = (123, 456) I think having "Boom!" (an exception) when your pattern doesn't match is the right thing to do, at least by default. But if you want to get fancy, we can supply a missing value: spam, eggs, cheese = sscanf("%d %d %d", "123 432", missing=None) assert spam == 123 assert eggs == 432 assert cheese is None -- Steve