On 26.05.2016 19:11, Paul Moore wrote:
On 26 May 2016 at 17:21, Sven R. Kunze <srkunze@mail.de> wrote:
I think "test one thing against multiple conditions" is a quite abstract thing to do.

I would like to see some real-world use-case for this kind of syntax
Today, I was parsing a job output file. For each line in the file, I
tested it against various patterns/conditions to see what type of line
it was. Depending on the type of line, I did something different. I
used a chain of if/elif statements, because that's what Python
currently (3.5) provides, but it would have been an obvious case for a
match/switch statement. If the important thing here is *structural*
matching then what I actually did was call split() on the line to get
a list of elements, then wanted some to be constants, and I picked
data out of others. Something like

    match line_parts:
        case _, 'Job', 'Start', start_time: do_something1(start_time)
        case _, 'Job', 'End', end_time: do_something2(end_time)
        case view, 'size', 'is', kb, 'KB': do_something3(view, kb)

Is that the type of example you had in mind?
Paul

Interesting to see that you chose chains of if-elses.

I wouldn't.

Especially because our guidelines tells us to avoid elses and ifs if possible. But here, it's also my personal preference of avoiding a switch-case-like mess.

So, in this particular case, I would have used a datastructure for describing how to work with the incoming data. That gives me three advantages over a syntax-using solution:

1) a datastructure (like a dict) would be first-class and I could move it around, manipulate it etc for whatever reason
2) I am able to run separate tests for the matching algorithm (aka finding the right mapping) without applying mocks for all possible match-cases
3) no monolithic code block that tends to grow


It is also interesting to see that it worked for you. I can remember a similar task quite some time ago. However, there, I needed regular expressions to solve the issue at hand. So, a simple structural unpacking didn't suffice. However, a loop over a list of (regex, action)s with a single check made it work for me.

Btw. Django uses this way of matching for the URLs system. And because it needs to be modular (different apps can contribute to it), it would be pointless to have a syntax for it. Even dynamic changes would not be possible with syntax which we do in various places because of, well let's call it, our customer requirements. ;-)


My point here is not that not somebody could make use of it (apparently it would for you). However, the absence of it forces people to invent other more flexible mechanisms and I'd actually like it this way.


This said, I could rather imagine a new function introduced to functools which provides some sort of match-and-dispatch functionality which you actually do above. Not sure if somebody already suggested this on this thread.


Best,
Sven